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.
Given a string containing only digits '0'-'9'
, write a function to determine if it's an additive number.
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03
or 1, 02, 3
is invalid.
Example 1:
Input:"112358"
Output: true Explanation: 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
Example 2:
Input:"199100199"
Output: true Explanation: The additive sequence is:1, 99, 100, 199
. 1 + 99 = 100, 99 + 100 = 199
Follow up:
How would you handle overflow for very large input integers?
这道题是典型的穷举,但是需要注意题目最后的要求:如何处理非常大的数。因为我们要使用加法,如果加数超出了整型能够表示的范围,那么就有可能出错,所以我这里使用了自己实现的字符串加法,这样不管多大的数都可以处理了。
class Solution {
public:
bool isAdditiveNumber(string num) {
for (int i = 1; i <= num.size() - i; i++) {
if (num[0] == '0' && i > 1) continue;
for (int j = 1; j <= num.size() - i - j; j++) {
if (num[i] == '0' && j > 1) continue;
string strA(num.begin(), num.begin() + i);
string strB(num.begin() + i, num.begin() + i + j);
string s(num.begin() + i + j, num.end());
if (helper(strA, strB, s)) return true;
}
}
return false;
}
private:
bool helper(string strA, string strB, string s) {
if (s[0] == '0' && s.size() > 1) return false;
int len = max(strB.size(), strA.size());
while (len <= s.size() && len <= max(strA.size(), strB.size()) + 1) {
string strC = s.substr(0, len);
if (strC == addStr(strA, strB)) {
if (len == s.size()) return true;
string strS = s.substr(len);
return helper(strB, strC, strS);
}
len++;
}
return false;
}
string addStr(string a, string b) {
int flag = 0;
string res = "";
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int maxLen = max(a.size(), b.size());
for (int i = 0; i < maxLen; i++) {
int sum = flag;
if (i < a.size()) sum += a[i] - '0';
if (i < b.size()) sum += b[i] - '0';
flag = sum / 10;
sum %= 10;
res = to_string(sum) + res;
}
if (flag == 1) res = "1" + res;
return res;
}
};