LeetCode 306 Additive Number

来源:互联网 发布:c语言打开方式w,wb 编辑:程序博客网 时间:2024/05/01 16:40

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?

这道题目,没有找到更喜欢的做法,所以brute force暴力解决。

public boolean isAdditiveNumber(String num) {int len = num.length();for (int i = 1; i <= len / 2; i++) {for (int j = 1; Math.max(i, j) <= len - j - i; j++) {String s1 = num.substring(0, i), s2 = num.substring(i, j + i);if (s1.charAt(0) == '0' && s1.length() > 1 || s2.charAt(0) == '0' && s2.length() > 1)continue;Long d1 = new Long(s1), d2 = new Long(s2), sum = d1 + d2;String next = sum.toString(), now = s1 + s2 + next;while (now.length() < len && num.startsWith(now)) {d1 = d2;d2 = sum;sum = d1 + d2;now += sum.toString();}if (now.equals(num)) return true;}}return false;}


再贴一个看着稍微顺眼的写法吧,比上面的快了1ms。感谢此博客

public boolean isAdditiveNumber2(String num) {for (int i = 1; i <= num.length() / 2; i++)for (int j = 1; Math.max(i, j) <= num.length() - j - i; j++)if (isValid(num, num.substring(0, i), num.substring(i, i + j), i + j)) return true;return false;}private boolean isValid(String num, String first, String second, int index) {if (first.length() > 1 && first.startsWith("0")|| second.length() > 1 && second.startsWith("0")) return false;if (index == num.length()) return true;long sum = Long.parseLong(first) + Long.parseLong(second);if (num.startsWith(sum + "", index))if (isValid(num, second, sum + "", index + (sum + "").length())) return true;return false;}


0 0
原创粉丝点击