[leetcode] 306. Additive Number

Additive number is a string whose digits can form additive sequence.git

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.spa

For example:
"112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.code

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.orm

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.blog

Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.three

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

 

Solution:string

 1  bool isAdditiveNumber(string num) 
 2     {
 3         for (int i = 1; i < num.size(); i++)
 4         {
 5             for (int j = i + 1; j < num.size(); j++)
 6             {
 7                 string s1 = num.substr(0, i);
 8                 string s2 = num.substr(i, j - i);
 9                 long long d1 = atoll(s1.c_str()); 
10                 long long d2 = atoll(s2.c_str());
11                 if ((s1.size() > 1 && s1[0] == '0') || (s2.size() > 1 && s2[0] == '0')) 
12                     continue; 
13                 
14                 long long dnext = d1 + d2;
15                 string snext = to_string(dnext);
16                 string scur = s1 + s2 + snext;
17                 while (scur.size() < num.size())
18                 {
19                     if (scur != num.substr(0, scur.size()))
20                     {
21                         break;
22                     }
23                     d1 = d2;
24                     d2 = dnext;
25                     dnext = d1 + d2;
26                     snext = to_string(dnext);
27                     scur += snext;
28                 }
29                 if (scur == num)
30                     return true;
31             }
32         }
33         
34         return false;
35     }
相關文章
相關標籤/搜索