[leetcode] Additive Number


Additive number is a positive integer 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 represents an integer, write a function to determine if it’s an additive number.

Follow up:
How would you handle overflow for very large input integers?

Credits:
Special thanks to @jeantimex for adding this problem and creating all test cases.

 

class Solution {
public:
    bool isAdditiveNumber(string num) {
        if(num.size() < 3) return false;
        for(int i = 1; i <= num.size() / 2; i++){
            for(int j = i + 1; j < num.size(); j++){// j < nums.size() - 1 to guarantee do not leave nums.substr(j, -1) empty
                string first = num.substr(0, i);
                string second = num.substr(i, j - i);
                bool state = DFS(num.substr(j, -1), first, second);
                if(state == true) return true;
            }
        }
        return false;
    }
    bool DFS(string num, string first, string second){
        if(num.empty()) return true;
        if((first[0] == '0' && first.size() > 1) || (second[0] == '0' && second.size() > 1)) return false; // leading nums
        string sumStr = addStr(first, second);
        if(num.substr(0, sumStr.size()) != sumStr){
            return false;
        }
        else{
            return DFS(num.substr(sumStr.size(), -1), second, sumStr);
        }
    }
    string addStr(string a, string b){
        int carry = 0;
        if(a.size() > b.size()){
            swap(a, b);
        }
        int i = a.size() - 1;
        int j = b.size() - 1;
        // a is shorter or equal to b
        while(j >= 0){
            int digit;
            if(i < 0){
                digit = b[j] - '0' + carry;
            }
            else{
                digit = a[i] + b[j] - '0' - '0' + carry;
            }
            if(digit >= 10){
                digit -= 10;
                carry = 1;
            }else{
                carry = 0;
            }
            b[j] = digit + '0';
            i--;
            j--;
        }
        if(carry == 1){
            b.insert(0, "1");
        }
        return b;
    }
};

 

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.