Simple java solution


  • 9
    H
    public boolean isAdditiveNumber(String num) {
        String a = "";
        String b = "";
        for (int i = 0; i < num.length()/3; i++) {
            a = num.substring(0, i + 1);
            if (a.length() > 1 && a.charAt(0) == '0') {
                continue;
            }
            for (int j = i + 1; j < num.length(); j++) {
                b = num.substring(i + 1, j + 1);
                if (b.charAt(0) == '0' && b.length() > 1) {continue;}
                if (valid(num.substring(j + 1), Long.parseLong(a), Long.parseLong(b))) {
                    return true;
                }
            }
        }
        return false;
    }
    public boolean valid(String str, long a, long b) {
        long sum = a + 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(str.substring(len), b, sum);
        }
        return false;
    }

  • 1
    Y

    The code fails at this case "0235813"
    To fix it, just need to verify whether "String a" has leading 0 if a has more than one digit, like what you did for String b.

    After

    a = num.substring(0, i + 1);
    

    add

    if (a.charAt(0) == '0' && a.length() > 1) {continue;}

  • 0
    D

    I think you can replace "continue" with "break".


  • 0
    A

    This code doesn't work for the test case : "199111992".


  • 0
    A

    ''' It should be num.length()/3 + 1, in the 1st for loop.


Log in to reply
 

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