306 Additive Number

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?

Solution

class Solution {
public:
    string add(string a, string b) {
        int na = a.size(), nb = b.size();
        int add = 0;
        int ia = na-1, ib = nb-1;
        int va, vb;
        string res = "";
        while ( ia >= 0 or ib >= 0 ) {
            if ( ia < 0 ) va = 0;
            else va = stoi(a.substr(ia--, 1));
            if ( ib < 0 ) vb = 0;
            else vb = stoi(b.substr(ib--, 1));
            res = to_string((va+vb+add)%10) + res;
            add = (va+vb+add)/10;
        }
        if ( add != 0 ) res = to_string(add) + res;
        return res;
    }
    bool isAdditive(string num, string a, string b ) {
        string sum = add(a, b);
        int n = num.size(), ns = sum.size();
        if ( n < ns ) return false;
        if ( num.substr(0, ns) != sum ) return false;
        if ( n == ns ) return true;
        return isAdditive(num.substr(ns), b, sum);
    }
    bool isAdditiveNumber(string num) {
        int n = num.size();
        if ( n < 3 ) return false;
        int i = 1, j = 1;
        for ( int i = 1; i <= n; i++ ) {
            for ( int j = 1; j <= n; j++ ) {
                if ( i+j+max(i, j) > n ) break;
                string a = num.substr(0, i);
                string b = num.substr(i, j);
                if ( i != 1 and a[0] == '0' ) continue;
                if ( j != 1 and b[0] == '0' ) continue;
                if (isAdditive(num.substr(i+j), a, b)) return true;
            }
        }
        return false;
    }
};

这道题不难,但是要注意几个corner case:

```101

results matching ""

    No results matching ""