-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAdditive-sequence.java
79 lines (65 loc) · 1.92 KB
/
Additive-sequence.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// User function Template for Java
class Solution {
public boolean isAdditiveSequence(String n) {
for(int i = 0; i < n.length() / 2; i++){
for(int j = i + 1; j < n.length() - 1; j++){
String x = n.substring(0, i + 1);
String y = n.substring(i + 1, j + 1);
String z = n.substring(j + 1);
if(helper(x, y, z)){
return true;
}
}
}
return false;
}
private static boolean helper(String x, String y, String z){
String s = calcSum(x, y);
int i = 0, j = 0;
while(i < z.length() && j < s.length()){
if(z.charAt(i) != s.charAt(j)){
return false;
}
i++;
j++;
}
if(j != s.length()){
return false;
}
if(i == z.length()){
return true;
}
z = z.substring(i);
return helper(y, s, z);
}
private static String calcSum(String x, String y){
int i = x.length() - 1;
int j = y.length() - 1;
StringBuilder res = new StringBuilder();
int c = 0;
while(i >= 0 && j >= 0){
int s = (x.charAt(i) - '0') + (y.charAt(j) - '0') + c;
res.append((char) s % 10);
c = s / 10;
i--;
j--;
}
while(i >= 0){
int s = (x.charAt(i) - '0') + c;
res.append((char) s % 10);
c = s / 10;
i--;
}
while(j >= 0){
int s = (y.charAt(j) - '0') + c;
res.append((char) s % 10);
c = s / 10;
j--;
}
if(c != 0){
res.append((char) (c + '0'));
}
StringBuilder tmp = res.reverse();
return tmp.toString();
}
}