# Middle-题目90：306. Additive Number

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.

Additive Number 的定义是，可以拆成至少3个子串，其中任意前两个子串对应数字的和都等于后一个子串。

import java.math.BigInteger;

public class Solution {
public boolean isAdditiveNumber(String num) {
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));
BigInteger sum = num1.add(num2);
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
result = result || isAdditiveNumber(num.substring(i+1));
}
}
}
return result;
}
}

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

• 本文已收录于以下专栏：

举报原因： 您举报文章：Middle-题目90：306. Additive Number 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)