306. Additive Number

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?


Code

public class Solution {
    public boolean isAdditiveNumber(String num) {
        if (num == null || num.length() == 0) return false;

        for (int i = 1; i < num.length() / 2 + 1; i++) {
            for (int j = i + 1; j <= num.length() && j - i <= num.length() / 2 + 1; j++) {
                String s1 = num.substring(0, i);
                String s2 = num.substring(i, j);
                if ((s1.charAt(0) == '0' && s1.length() > 1) || (s2.charAt(0) == '0' && s2.length() > 1)) continue;
                long i1 = Long.parseLong(s1);
                long i2 = Long.parseLong(s2);
                long sum = i1 + i2;
                int flag = 0;
                int k = j;
                while (k + String.valueOf(sum).length() <= num.length()) {
                    long i3 = Long.parseLong(num.substring(k, k + String.valueOf(sum).length()));
                    if (i3 == sum) {
                        i1 = i2;
                        i2 = i3;
                        k += String.valueOf(sum).length();
                        sum = i1 + i2;
                        flag = 1;
                    } else {
                        flag = 2;
                        break;
                    }
                }
                if (flag == 1) return true;
            }
        }
        return false;
    }
}

Solution

关键在于找出前两个数,后面的数则可以依次做对比。
对前两个数进行枚举。

你可能感兴趣的:(306. Additive Number)