-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d505512
commit 6d74b5b
Showing
1 changed file
with
98 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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; | ||
} | ||
} |