C++ simple 0ms.


  • 0
    P

    Unbelievable the first time I submit it, it got accepted!

    string add(string a, string b) {
        string ans;
        if (a.size() < b.size()) swap(a,b);
        b = string(a.size()-b.size(), '0') + b;
        int carry = 0;
        for (int i = a.size()-1;i >= 0;--i) {
            ans =  char((a[i]-'0'+b[i]-'0'+carry)%10 + '0') + ans;
            carry = (a[i]-'0'+b[i]-'0'+carry) / 10;
        }
        if (carry > 0)
            ans = char(carry + '0') + ans;
        return ans;
    }
    
    bool isAdditiveNumber(string num) {
        int len = num.size();
        for (int l = 2;l <= len/3*2;++l) {
            for (int i = 1;i <= l-1;++i) {
                int firstL = i, totalL = l, start = 0;
                do {
                    if (num[start] == '0' && firstL > 1 || num[start+firstL] == '0' && totalL-firstL>1) break;
                    string a = add(num.substr(start,firstL),num.substr(start+firstL,totalL-firstL));
                    if (a.size()+totalL+start > num.size())
                        break;
                    if (a != num.substr(totalL+start,a.size()))
                        break;
                    if (a.size()+totalL+start == num.size())
                        return true;
                    start = start + firstL;
                    firstL = totalL-firstL;
                    totalL = firstL+a.size();
                } while (true);             
            }
        }
        return false;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.