Easy To Understand JAVA Code


  • 0
    Y
    import java.math.BigInteger;
     public class Solution {
        public boolean isAdditiveNumber(String num) {
            for(int i =1;i<= num.length()/2;i++){ // i is the end of the index for value a, exclusive
                if(num.charAt(0)=='0' && i != 1)
                    break;
                BigInteger a = new BigInteger(num.substring(0,i));
                for(int j = i; j< num.length()-1; j++){ // j is the end of the index for value b, inclusive
                    if(num.charAt(i) =='0' && j != i)
                        break;
                    BigInteger b = new BigInteger(num.substring(i,j+1));
                    if(valid(a, b, num.substring(j+1)))
                        return true;
                }
            }
            return false;
        }
        public boolean valid(BigInteger a, BigInteger b,String str) {
        BigInteger sum = a.add(b);
        String tempStr = String.valueOf(sum);
        int len = tempStr.length();
        if (str.length() < len) {return false;}
        if (str.length() == len && str.equals(tempStr)) {return true;}
        if (str.substring(0, len).equals(tempStr)) {
            return valid(b, sum,str.substring(len));
        }
        return false;
    }
    }
    
    

Log in to reply
 

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