0306.cpp (868B)
1 class Solution { 2 public: 3 bool isAdditiveNumber(const string &num) { 4 for (int i = 1; i < num.size(); i++) { 5 long num1 = stol(num.substr(0, i)); 6 for (int j = i + 1; j < num.size(); j++) { 7 long n1 = num1, n2 = stol(num.substr(i, j - i)), n3; 8 int next = j; 9 while (next < num.size()) { 10 const string pre = to_string(n3 = n1 + n2); 11 12 auto res = std::mismatch(pre.begin(), pre.end(), num.substr(next).begin()); 13 if (res.first != pre.end()) break; 14 15 next += pre.size(); 16 n1 = n2, n2 = n3; 17 } 18 if (next == num.size()) return true; 19 if (num[i] == '0') break; 20 } 21 if (num[0] == '0') break; 22 } 23 return false; 24 } 25 };