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?
特殊的例子,101,可以分隔为1,0,1,也就是说,单个的0也是允许的。那么首先需要确认第一个数和第二个数,将两个数相加,得到第三个数,判断第二个数之后是否有对应的子串,比如说,abcdefg,首先假设第一个数和第二个数为a和b,那么计算出a+b得到一个数x,判断cdefg中是否存在从头开始的子串。如果不存在,这说明第一个数或者第二个数不正确。然后重复这个过程。其中如果字符串太长的话,那么将字符串转换成数字时,会造成溢出状况,所以采取字符串做数字加法的方式。利用DFS的方法,每一层都将当前的两个数传给下一层,在下一层中判断是否存在上一层的两个数的字符串和,如果存在,则继续进入下一层,否则,则返回false。其中要考虑0可以存在,但是02不能存在的情况,所以当某一个子串的开头为'0'时,则将此子串限制为'0',按照上面的过程运算。
Code:
string add(string a, string b)
{
string result = "";
if (b.length() > a.length()) { string temp = a; a = b; b = temp; }
int i = a.length() - 1, j = b.length() - 1;
int c = 0;
while (i >= 0)
{
int temp = a[i] - 48 + (j >= 0 ? (b[j] - 48) : 0) + c;
c = temp > 9 ? 1 : 0;
temp %= 10;
result = to_string(temp) + result;
i--;
j--;
}
return (c != 0 ? to_string(c) : "") + result;
}
bool helper(string first, string second, string num_string)
{
if (num_string == "")return true;
if (num_string[0] == '0' && (first != "0" || second != "0"))return false;
string third = add(first, second);
if (num_string.substr(0, third.length()) != third)return false;
return helper(second, third, num_string.substr(third.length()));
}
bool isAdditiveNumber(string num)
{
if (num == "" || num.length() < 3)return false;
int first = 0, second = 0;
for (int i = 1; i <= num.length() - 2; i++)
{
for (int j = 1; j <= num.length() - i - 1; j++)
{
if (num[i] == '0')
{
if (helper(num.substr(0, i), "0", num.substr(i + j)))return true;
break;
}
if (helper(num.substr(0, i), num.substr(i, j), num.substr(i + j)))return true;
}
}
return false;
}