java 5ms recursive solution easy to follow.


  • 0
    S
        public boolean isAdditiveNumber(String num) {
            
            for(int i = 1; i < num.length(); i++){
                for(int j = 1; j < num.length(); j++){
                    if(isAdditiveNumberRecurse(num, 0,i,i+j, i, j, 1)){
                        return true;
                    }
                }
            }
            
            return false;
            
            
    
        }
        
        public boolean isAdditiveNumberRecurse(String num, int x, int y, int z, int dx, int dy, int dz){
            if(z> num.length()-1 || z + dz > num.length()){
                return false;
            }
            else{
                String tempxStr = num.substring(x, x+dx);
                String tempyStr = num.substring(y, y+dy);
                String tempzStr = num.substring(z, z+dz);
                Long tempx = Long.parseLong(tempxStr);
                Long tempy = Long.parseLong(tempyStr);
                Long tempz = Long.parseLong(tempzStr);
                if((tempxStr.charAt(0) == '0' && tempxStr.length() > 1) || 
                (tempyStr.charAt(0) == '0'  && tempyStr.length() > 1) || 
                tempzStr.charAt(0) == '0' && tempyStr.length()>1){
                    return false;
                }
                else if(tempx+tempy == tempz && z + dz == num.length()){
                    return true;
                } 
                else if(tempx+tempy == tempz){
                    return isAdditiveNumberRecurse(num, y, z, z+dz, dy, dz, 1);
                } 
                else{
                    String strTempz = num.substring(z, z+dz);
                    String strTempzCompare = String.valueOf(tempx + tempy);
                    if(strTempz.length() < strTempzCompare.length()){
                        int diff = strTempzCompare.length() - strTempz.length();
                        return isAdditiveNumberRecurse(num, x, y, z, dx, dy, dz + diff);
                    }
                    else{
                        return false;
                    }
                }
            }
        }

Log in to reply
 

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