Additive number is a string whose digits can form Additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first and numbers, each subsequent number in the sequence must is the sum of the preceding.
For example:
"112358"
is a additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8
.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
"199100199"
is also a additive number, the additive sequence is: 1, 99, 100, 199
.
1 + 99 = 100, 99 + 100 = 199
Note:numbers in the additive sequence cannot has leading zeros, so sequence 1, 2, 03
or is 1, 02, 3
invalid.
Given a string containing only digits ‘0‘-‘9‘
, write a function to determine if it's an additive number.
Follow up:
How would handle overflow for very large input integers?
1 classSolution {2 Public:3 BOOLCheckstringSTR1,stringSTR2,stringstr)4 {5 6 StringStream SS1;7 stringSTR3;8 Longnum1, num2, num3;9SS1 <<str1;TenSS1 >>NUM1; One ss1.clear (); ASS1 <<str2; -SS1 >>num2; - ss1.clear (); thenum3 = Num1 +num2; -SS1 <<num3; -SS1 >>STR3; - ss1.clear (); + -cout << NUM1 <<" "<< num2 <<" "<< num3 <<Endl; + A if(STR3 = =str) at { - return true; - } - if(Str.size () < Str3.size () | | Str3.compare (STR.SUBSTR (0, Str3.size ()))! =0) - { - return false; in } - Else to { + returnCheck (str2, STR3, Str.substr (Str3.size ())); - } the } * $ BOOLIsadditivenumber (stringnum) {Panax Notoginseng intL =num.length (); - the for(inti =1; I <= (L-1) /2; ++i) + { A if(num[0] =='0'&& I >=2) the { + Break; - } $ for(intj =1; (L-i-J) >= I && (L-i-J) >= J; ++j) $ { - if(Num[i] = ='0'&& J >=2) - { the Break; - }Wuyi the stringSTR1 = Num.substr (0, i); - stringSTR2 =Num.substr (i, j); Wu - if(Check (str1, str2, num.substr (i +J ))) About { $ return true; - } - - } A } + return false; the } -};
306. Additive number