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 two numbers, each subsequent number in the sequence must be the sum of the preceding two.
For example:"112358"
is an 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 an additive number, the additive sequence is: 1, 99, 100, 199
.
1 + 99 = 100, 99 + 100 = 199
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03
or 1, 02, 3
is invalid.
Given a string containing only digits ‘0‘-‘9‘
, write a function to determine if it‘s an additive number.
Follow up:
How would you handle overflow for very large input integers?
1 class Solution { 2 public: 3 bool check(string str1, string str2, string str) 4 { 5 6 stringstream ss1; 7 string str3; 8 long num1, num2, num3; 9 ss1 << str1; 10 ss1 >> num1; 11 ss1.clear(); 12 ss1 << str2; 13 ss1 >> num2; 14 ss1.clear(); 15 num3 = num1 + num2; 16 ss1 << num3; 17 ss1 >> str3; 18 ss1.clear(); 19 20 cout << num1 << " " << num2 << " " << num3 << endl; 21 22 if (str3 == str) 23 { 24 return true; 25 } 26 if (str.size() < str3.size() || str3.compare(str.substr(0,str3.size())) != 0) 27 { 28 return false; 29 } 30 else 31 { 32 return check(str2, str3, str.substr(str3.size())); 33 } 34 } 35 36 bool isAdditiveNumber(string num) { 37 int L = num.length(); 38 39 for (int i = 1; i <= (L - 1) / 2; ++i) 40 { 41 if (num[0] == ‘0‘ && i >= 2) 42 { 43 break; 44 } 45 for (int j = 1; (L - i - j) >= i && (L - i - j) >= j; ++j) 46 { 47 if (num[i] == ‘0‘ && j >= 2) 48 { 49 break; 50 } 51 52 string str1 = num.substr(0, i); 53 string str2 = num.substr(i, j); 54 55 if (check(str1, str2, num.substr(i + j))) 56 { 57 return true; 58 } 59 60 } 61 } 62 return false; 63 } 64 };
时间: 2024-10-03 23:00:38