306. Additive Number

来源:互联网 发布:java未来五年发展前景 编辑:程序博客网 时间:2024/05/16 10:31

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.

思路:就是三重循环判断

代码如下(已通过leetcode)

public class Solution {
public boolean isAdditiveNumber(String num) {

for (int i = 0; i < num.length() - 2; i++) {
long a;
if(num.substring(0,i+1).charAt(0)=='0'&&num.substring(0,i+1).length()!=1) break;
else a = Long.valueOf(num.substring(0, i + 1));



for (int j = i + 1; j < num.length() - 1; j++) {
long b;
if(num.substring(i+1,j+1).charAt(0)=='0'&&num.substring(i+1,j+1).length()!=1) break;
else b = Long.valueOf(num.substring(i + 1, j + 1));

for (int k = j + 1; k < num.length(); k++) {
long c;
if(num.substring(j+1,k+1).charAt(0)=='0'&&num.substring(j+1,k+1).length()!=1) break;
else c = Long.valueOf(num.substring(j + 1, k + 1));
//System.out.println("a: " + a + "  " + "b: " + b + "  " + "c: " + c);
if (a + b == c) {
boolean flag = true;
int temp = k + 1;
if(k+1>=num.length()) return true;
int len=0;
while (temp+len <=num.length()) {
c=a+b;
//System.out.println("a: " + a + "  " + "b: " + b + "  " + "c: " + c);

a = b;
b = c;

long count = a + b;
len = (count + "").length();
if (a + b != Long.valueOf(num.substring(temp, temp + len))) {
flag = false;
break;
} else {
temp = temp + len;
}



}
if (flag)
return true;
} else {
a=Long.valueOf(num.substring(0, i + 1));
b=Long.valueOf(num.substring(i + 1, j + 1));
if(a+b<c) break;
}
}
}


}
return false;
}
}

0 0
原创粉丝点击