美文网首页计算机Leetcode, again
Leetcode - Additive Number

Leetcode - Additive Number

作者: Richardo92 | 来源:发表于2016-10-15 02:22 被阅读19次

    My code:

    import java.math.BigInteger;
    
    public class Solution {
        public boolean isAdditiveNumber(String num) {
            int n = num.length();
            for (int i = 1; i <= n / 2; i++) {
                for (int j = 1; Math.max(i, j) <= n - i - j; j++) {
                    if (isValid(i, j, num)) {
                        return true;
                    }
                }
            }
            return false;
        }
        
        private boolean isValid(int i, int j, String num) {
            if (num.charAt(0) == '0' && i > 1) {
                return false;
            }
            if (num.charAt(i) == '0' && j > 1) {
                return false;
            }
            String sum = "";
            BigInteger x1 = new BigInteger(num.substring(0, i));
            BigInteger x2 = new BigInteger(num.substring(i, i + j));
            for (int start = i + j; start != num.length(); start += sum.length()) {
                x2 = x2.add(x1);
                x1 = x2.subtract(x1);
                sum = x2.toString();
                if (!num.startsWith(sum, start)) {
                    return false;
                }
            }
            return true;
        }
    }
    

    reference:
    https://discuss.leetcode.com/topic/29856/java-recursive-and-iterative-solutions

    解释的很好。

    Anyway, Good luck, Richardo! -- 10/14/2016

    相关文章

      网友评论

        本文标题:Leetcode - Additive Number

        本文链接:https://www.haomeiwen.com/subject/lfmnyttx.html