累加數(shù) 是一個(gè)字符串眷射,組成它的數(shù)字可以形成累加序列焚廊。
一個(gè)有效的 累加序列 必須 至少 包含 3 個(gè)數(shù)知允。除了最開始的兩個(gè)數(shù)以外闯捎,字符串中的其他數(shù)都等于它之前兩個(gè)數(shù)相加的和椰弊。
給你一個(gè)只包含數(shù)字 '0'-'9' 的字符串许溅,編寫一個(gè)算法來判斷給定輸入是否是 累加數(shù) 。如果是秉版,返回 true 贤重;否則,返回 false 清焕。
說明:累加序列里的數(shù) 不會 以 0 開頭并蝗,所以不會出現(xiàn) 1, 2, 03 或者 1, 02, 3 的情況。
示例 1:
輸入:"112358"
輸出:true
解釋:累加序列為: 1, 1, 2, 3, 5, 8 秸妥。1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
示例 2:
輸入:"199100199"
輸出:true
解釋:累加序列為: 1, 99, 100, 199滚停。1 + 99 = 100, 99 + 100 = 199
提示:
1 <= num.length <= 35
num 僅由數(shù)字(0 - 9)組成
java代碼:
class Solution {
public boolean isAdditiveNumber(String num) {
int n = num.length();
for (int secondStart = 1; secondStart < n - 1; ++secondStart) {
if (num.charAt(0) == '0' && secondStart != 1) {
break;
}
for (int secondEnd = secondStart; secondEnd < n - 1; ++secondEnd) {
if (num.charAt(secondStart) == '0' && secondStart != secondEnd) {
break;
}
if (valid(secondStart, secondEnd, num)) {
return true;
}
}
}
return false;
}
public boolean valid(int secondStart, int secondEnd, String num) {
int n = num.length();
int firstStart = 0, firstEnd = secondStart - 1;
while (secondEnd <= n - 1) {
String third = stringAdd(num, firstStart, firstEnd, secondStart, secondEnd);
int thirdStart = secondEnd + 1;
int thirdEnd = secondEnd + third.length();
if (thirdEnd >= n || !num.substring(thirdStart, thirdEnd + 1).equals(third)) {
break;
}
if (thirdEnd == n - 1) {
return true;
}
firstStart = secondStart;
firstEnd = secondEnd;
secondStart = thirdStart;
secondEnd = thirdEnd;
}
return false;
}
public String stringAdd(String s, int firstStart, int firstEnd, int secondStart, int secondEnd) {
StringBuffer third = new StringBuffer();
int carry = 0, cur = 0;
while (firstEnd >= firstStart || secondEnd >= secondStart || carry != 0) {
cur = carry;
if (firstEnd >= firstStart) {
cur += s.charAt(firstEnd) - '0';
--firstEnd;
}
if (secondEnd >= secondStart) {
cur += s.charAt(secondEnd) - '0';
--secondEnd;
}
carry = cur / 10;
cur %= 10;
third.append((char) (cur + '0'));
}
third.reverse();
return third.toString();
}
}