-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution306.java
55 lines (48 loc) · 1.42 KB
/
Solution306.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package algorithm.leetcode;
/**
* @author: mayuan
* @desc: 累加数
* @date: 2018/08/13
*/
public class Solution306 {
public static void main(String[] args) {
Solution306 test = new Solution306();
String str = "11235813213455890144";
System.out.println(test.isAdditiveNumber(str));
}
public boolean isAdditiveNumber(String num) {
int length = num.length();
if (length < 3) {
return false;
}
// i 和 j 分别是第一个和第二个数字的长度
for (int i = 1; i <= length / 2; ++i) {
for (int j = 1; Math.max(i, j) <= length - i - j; ++j) {
if (isValid(num, i, j)) {
return true;
}
}
}
return false;
}
private boolean isValid(String num, int i, int j) {
if (num.charAt(0) == '0' && 1 < i) {
return false;
}
if (num.charAt(i) == '0' && 1 < j) {
return false;
}
String sum = "";
Long x1 = Long.parseLong(num.substring(0, i));
Long x2 = Long.parseLong(num.substring(i, i + j));
for (int start = i + j; start != num.length(); start += sum.length()) {
x2 = x1 + x2;
x1 = x2 - x1;
sum = x2.toString();
if (!num.startsWith(sum, start)) {
return false;
}
}
return true;
}
}