码迷,mamicode.com
首页 > 其他好文 > 详细

Additive Number

时间:2015-11-26 09:31:39      阅读:375      评论:0      收藏:0      [点我收藏+]

标签:

没啥好说的,注意用long(明明题目里说integer,汗)

public class Solution {
    public boolean isAdditiveNumber(String num) {
        int length = num.length();
        int i = 1;
        while (i < length && Long.valueOf(num.substring(0, i)) <= Integer.MAX_VALUE) {
            int j = i + 1;
            while (j <= length && Long.valueOf(num.substring(i, j)) <= Integer.MAX_VALUE) {
                if ((num.substring(0, i).length() > 1 && num.substring(0, i).startsWith("0")) || (num.substring(i, j).length() > 1 && num.substring(i, j).startsWith("0"))) {
                    break;
                }
                long first = Integer.valueOf(num.substring(0, i));
                long second = Integer.valueOf(num.substring(i, j));
                if (num.substring(j).length() == 0) {
                    break;
                }
                if (isvalid(first, second, num.substring(j))) {
                    return true;
                }
                j ++;
            }
            i ++;
        }
        return false;
    }
    public boolean isvalid(long first, long second, String num) {
        if (num.length() == 0) {
            return true;
        }
        long third = first + second;
        if (num.length() >= String.valueOf(third).length() && num.substring(0, String.valueOf(third).length()).equals(String.valueOf(third))) {
            return isvalid(second, third, num.substring(String.valueOf(third).length()));
        }
        return false;
    }
}

 

Additive Number

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/4996589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!