Java implementation LeetCode 306 cumulative number

306. The cumulative number

Accumulating the number is a string, the composition can be formed that accumulate sequence numbers.

An effective accumulated sequence must contain at least three numbers. In addition to the beginning of the two numbers, the other is equal to the number of strings before it two numbers together and.

Contains only a given number '0' - string '9', to write a given algorithm determines whether the input number is cumulative.

Description: The sequence in the accumulated number does not start with 0, 1. 2, 03 or 1, 02, 3, it will not appear.

Example 1:

Input: "112358"
Output: true
explanation: the accumulated sequence: 1, 1, 2, 3, 5, 8. 1 + 1 = 2, 2 + 1 = 3, 3 + 2 = 5, 3 + 5 = 8
Example 2:

Enter: "199 100 199"
Output: true
explanation: cumulative sequence: 1, 99, 100, 199.1 + 99 = 100, 99 + 100 = 199
Advanced:
How do you handle an overflow of large integer input?

class Solution {
    public boolean isAdditiveNumber(String num) {
    if (num.length() < 3) return false;
    int n = num.length();
    for (int i = 1; i <= (n - 1) / 2; i++) {
        if (i > 1 && num.charAt(0) == '0') break;
        for (int j = i + 1; (n - j) >= i && (n - j) >= j - i; j++) {
            if (j - i > 1 && num.charAt(i) == '0') break;
            long num1 = Long.parseLong(num.substring(0, i));
            long num2 = Long.parseLong(num.substring(i, j));
            if (isAdditive(num.substring(j), num1, num2))
                return true;
        }
    }
    return false;
}

private boolean isAdditive(String remain, long num1, long num2) {
    if (remain.equals("")) return true;
    long sum = num1 + num2;
    String str = String.valueOf(sum);
    if (!remain.startsWith(str)) return false;
    return isAdditive(remain.substring(str.length()), num2, sum);
}
}
Released 1426 original articles · won praise 10000 + · views 1.53 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104685072