Solution using BigInteger


  • 0
    C
    import java.math.BigInteger;
    public class Solution {
        public boolean isAdditiveNumber(String num) {
            BigInteger[]  arr = new BigInteger[2];
           
            for(int i=0; i<num.length()/2; i++){
                BigInteger  num1 = new BigInteger(num.substring(0,i+1));
                for(int j=i+1; j<num.length(); j++){
                    
                    BigInteger num2 =  new BigInteger(num.substring(i+1, j+1));
                    BigInteger sum = num1.add(num2);
                    arr[0] = num1;
                    arr[1] = num2;
                    String s = num.substring(j+1);
                    if(s.length()>0 && isSum(s, arr)){
                        return true;
                    }
                    if(num.charAt(i+1)=='0')
                        break;
                }
            }
            return false;
        }
        
        public boolean isSum(String s, BigInteger[] arr){
            //System.out.println(""+s);
            if(s.length()==0)
                return true;
            BigInteger sum  = arr[0].add(arr[1]);
            for(int i=0; i<s.length(); i++){
                if(s.charAt(0)=='0')
                    return false;
                BigInteger temp = new BigInteger(s.substring(0,i+1));
                if(temp.compareTo(sum)==0){
                    arr[0] = arr[1];
                    arr[1] = temp;
                    return isSum(s.substring(i+1), arr);
                }else if(temp.compareTo(sum)==1)
                    return false;
            }
            return false;
        }
    
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.