diff --git a/Additive sequence b/Additive sequence new file mode 100644 index 0000000..09ed8ea --- /dev/null +++ b/Additive sequence @@ -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; + } +}