[LeetCode][JavaScript]Additive Number
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/
遍历,一个个找,最多找到长度的一半,再长就不可能了。
比如字符串是ABCDEFGH。
按照顺序找:
A+B, A+BC, A+BCD, ...
AB+C, AB+CD, ...
ABC+D, ABC+DE, ...
...
不过我是从后往前找的,感觉上可以减少一点次数。
F+G是否等于H, EF+G是否等于H, ...
E+FG是否等于H, DE+FG是否等于H, ...
...
E+F是否等于GH, DE+F是否等于GH, ...
...
以此类推。
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 str_len = str.length, numA, numB, A_len, B_len, i, j; 20 for(i = 1; i <= number.length; i++){ 21 A_len = str_len - i; 22 numA = str.substring(A_len, str_len); 23 if(!isValidNum(numA)) continue; 24 for(j = 1; j <= number.length; j++){ 25 B_len = str_len - i - j; 26 numB = str.substring(B_len, A_len); 27 if(!isValidNum(numB)) continue; 28 if(parseInt(numA) + parseInt(numB) === parseInt(number)){ 29 if(str.substring(0, B_len) === "") return true; 30 return checkTailNum(str.substring(0, A_len), str.substring(A_len, str_len)); 31 } 32 } 33 } 34 return false; 35 } 36 };