Leetcode-Additive Number(Java)

Question:

Additive number is a string whose digits can form additive sequence.

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

For example:
“112358” is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.

1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
“199100199” is also an additive number, the additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Given a string containing only digits ‘0’-‘9’, write a function to determine if it’s an additive number.

Follow up:
How would you handle overflow for very large input integers?

Thinking:

I noticed that it’s only different in the first time in the iteration becuase we know nothing about the first element. But when found it, we can use the previous two elements to check the next one. So in the first function, we enumerate the first two elements, and check the rest string if it’s valid recursively.

Solution:

public boolean isAdditiveNumber(String num) {

    int len = num.length();

    long num1 = 0;
    long num2 = 0;
    //find the first two elements first
    for (int i = 1; 2*i+1 <= len; i++){
        for (int j = 1; Math.max(i, j) <= len-i-j; j++){
            if (num.charAt(0) == '0' && i > 1)    return false;//if first char is 0, then it only can be 0
            num1 = Long.parseLong(num.substring(0, i));
            if (num.charAt(i) == '0' && j > 1)    break;//if second element start with 0, then it only can be 0
            num2 = Long.parseLong(num.substring(i, i+j));
            if (isValid(num1, num2, i+j, num))//check the rest recursively
                return true;
        }
    }

    return false;
}

private boolean isValid(long i, long j, int start, String num){
    if (start == num.length())    return true;//no rest chars left, success
    if (num.charAt(start) == '0')    return false;
    long sum = 0;
    for (int idx = start+1; idx <= num.length(); idx++){
        sum = Long.parseLong(num.substring(start, idx));
        if (sum - i > j)
            return false;
        if (sum - i == j)
            return isValid(j, sum, idx, num);
    }
    return false;
}