码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] 306. Additive Number

时间:2016-07-31 14:32:07      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

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:

 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     }

 

[leetcode] 306. Additive Number

标签:

原文地址:http://www.cnblogs.com/ym65536/p/5722936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!