-
Notifications
You must be signed in to change notification settings - Fork 0
/
Additive sequence
98 lines (78 loc) · 2.38 KB
/
Additive sequence
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//Additive sequence
import java.util.*;
public class GFG {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0) {
String s = sc.next();
Solution ss = new Solution();
boolean result = ss.isAdditiveSequence(s);
System.out.println((result == true ? 1 : 0));
}
sc.close();
}
}
class Solution {
static String findSum(String a, String b){
int i = a.length() - 1, j = b.length() - 1;
StringBuilder ans = new StringBuilder();
int carry = 0;
while(i >= 0 && j >= 0) {
int sum = (a.charAt(i) - '0') + (b.charAt(j) - '0') + carry;
ans.append((char)sum % 10);
carry = sum / 10;
i--;
j--;
}
while(i >= 0) {
int sum = (a.charAt(i) - '0') + carry;
ans.append((char)sum % 10);
carry = sum / 10;
i--;
}
while(j >= 0) {
int sum = (b.charAt(j) - '0') + carry;
ans.append((char)sum % 10);
carry = sum / 10;
j--;
}
if(carry != 0) {
ans.append((char)(carry + '0'));
}
StringBuilder temp = ans.reverse();
return temp.toString();
}
static boolean help(String a, String b, String c) {
String sum = findSum(a, b);
int i = 0, j = 0;
while(i < c.length() && j < sum.length()) {
if(c.charAt(i) != sum.charAt(j)) {
return false;
}
i++;
j++;
}
if(j != sum.length()) {
return false;
}
if(i == c.length()) {
return true;
}
c = c.substring(i);
return help(b, sum, c);
}
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 a = n.substring(0, i + 1);
String b = n.substring(i + 1, j + 1);
String c = n.substring(j + 1);
if(help(a, b, c)) {
return true;
}
}
}
return false;
}
}