Skip to content

Commit

Permalink
Create Additive sequence
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored Mar 26, 2024
1 parent d505512 commit 6d74b5b
Showing 1 changed file with 98 additions and 0 deletions.
98 changes: 98 additions & 0 deletions Additive sequence
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;
}
}

0 comments on commit 6d74b5b

Please sign in to comment.