AdSense

Monday, June 27, 2016

Additive Number

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?
Iterative each combination of first and second number, then recursively check if the whole sequence is valid.

 public boolean isAdditiveNumber(String num) {
        if (num == null || num.length() < 3)
            return false;
        int len = num.length();
        for (int f_pos = 1; f_pos < len; f_pos++) {
            for (int s_pos = f_pos + 1; s_pos < len; s_pos++) {
                if (isValid(num, 0, f_pos, s_pos))
                    return true;
            }
        }
        return false;
    }
    
    private boolean isValid(String num, int start, int f_pos, int s_pos) {
        int len = num.length();
        if ((f_pos - start > 1 && num.charAt(start) == '0') || (s_pos - f_pos > 1 && num.charAt(f_pos) == '0'))
            return false;
        long first = Long.parseLong(num.substring(start, f_pos));
        long second = Long.parseLong(num.substring(f_pos, s_pos));
        String sum = String.valueOf(first + second);
        int next_pos = s_pos + sum.length();
        
        if(next_pos > len || !num.substring(s_pos, next_pos).equals(sum))
            return false;
        return next_pos == len ? true : isValid(num, f_pos, s_pos, next_pos);
        
    }


No comments:

Post a Comment