85人阅读 评论(0)

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.

import java.math.BigInteger;

public class Solution {
int length = num.length();
boolean result = false;
for(int i = 0;i<length-1;i++){
//if(num.charAt(i+1)=='0')
//  continue;
String temp1 = num.substring(0, i+1);
if(temp1.length() > 1 && temp1.startsWith("0"))
continue;
BigInteger num1 = new BigInteger(num.substring(0, i+1)); // start: 0 ,end: i
for(int j= i+1;j<length-1;j++) {
String temp2 = num.substring(i+1,j+1);
if(temp2.length()>1 && temp2.startsWith("0"))
break;
BigInteger num2 = new BigInteger(num.substring(i+1,j+1));
if(num.length()-j-1<sum.toString().length())
break;
else if(num.substring(j+1, j+1+sum.toString().length()).equals(sum.toString())) {
if(1+j+sum.toString().length() == num.length()) {
result= true;
break;
}
else
}
}
}
return result;
}
}

23ms,beats 1.60%,众数3ms,39.48%
Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：55583次
• 积分：3194
• 等级：
• 排名：第10669名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论