码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Additive Number

时间:2015-11-18 23:04:05      阅读:767      评论:0      收藏:0      [点我收藏+]

标签:

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?

https://leetcode.com/problems/additive-number/

 

 

 


 

 

明天写思路。 

 

 1 /**
 2  * @param {string} num
 3  * @return {boolean}
 4  */
 5 var isAdditiveNumber = function(num) {
 6     var len = num.length, tail;
 7     for(var i = 1; i <= parseInt(num.length / 2); i++){
 8         tail = num.substring(len - i, len);
 9         if(!isValidNum(tail)) continue;
10         if(checkTailNum(num.substring(0, len - i), tail)) return true;
11     }
12     return false;
13     
14     function isValidNum(num){
15         if(num.length >= 2 && tail[0] === ‘0‘) return false;
16         return true;
17     }
18     function checkTailNum(str, number){
19         var len = str.length, numA, numB, i, j;
20         for(i = 1; i <= number.length; i++){
21             numA = str.substring(len - i, len);
22             if(!isValidNum(numA)) continue;
23             for(j = 1; j <= number.length; j++){
24                 numB = str.substring(len - i - j, len - i);
25                 if(!isValidNum(numB)) continue;
26                 if(parseInt(numA) + parseInt(numB) === parseInt(number)){
27                     if(str.substring(0, len - i - j) === "") return true;
28                     return checkTailNum(str.substring(0, len - i), str.substring(len - i, len));
29                 }
30             }
31         }
32         return false;
33     }
34 };

 

 

[LeetCode][JavaScript]Additive Number

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4976060.html

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