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?
实现:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string stringAdd(const string& a, const string& b)
{
int asize = a.length();
int bsize = b.length();
int max = asize > bsize ? asize : bsize;
int m = 0;
string newb;
string newa;
if (asize > bsize) {
newb = string(asize - bsize, '0');
newb.append(b);
newa = a;
}
else if (asize < bsize) {
newa = string(bsize - asize, '0');
newa.append(a);
newb = b;
}
else {
newa = a;
newb = b;
}
vector<char> result = vector<char>(max + 1);
for (int i = max - 1; i >= 0; --i)
{
int c = (newa[i] + newb[i] + m - 2 * '0');
m = c / 10;
char v = c % 10 + '0';
result[max-1-i] = v;
}
result[max] = ('0' + m);
string s = string(result.rbegin(), result.rend());
if (s[0] == '0')
return s.substr(1);
return s;
}
bool isAdditiveNumber(string num)
{
int size = num.length();
for (int j = 1; j <= size - 2; ++j)
{
string a = num.substr(0, j);
if (a[0] == '0' && j > 1)
continue;
for (int k = 1; k <= size - 1; ++k) {
string b = num.substr(j, k);
if (a[0] == '0' && k > 1)
continue;
string result = stringAdd(a, b);
if (j + k + result.length() > size)
continue;
string val = num.substr(j + k, result.length());
int pass = j + k;
string aa;
while (result.compare(val) == 0)
{
pass += val.length();
if (size == pass)
return true;
aa = b;
b = result;
result = stringAdd(aa, b);
val = num.substr(pass, result.length());
}
}
}
return false;
}