(Java)LeetCode-306. 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'
Follow up:
How would you handle overflow for very large input integers?
這道題是判斷一個數是不是“可加數”,題意比較明瞭,就不復述了。
首先我寫了一個函式private boolean check(String num, String first, String second),用來判斷以first 和 second開始的數num是不是可加數
接著就是遍歷所有的first和second可能,要注意,除去first和second之外剩下的字串長度一定要大於first和second中的較大者,所以first 、second最大是num長度的一半。
剛開始為了避免int會溢位,我採用了BigInteger來進行加法,不過這拖累了速度,需要10ms,後來我準備分段,很大的時候用BigInteger,小的時候用Long,不過在分段之前用Long型試了下也可以Accept,而且時間僅僅需要2ms,就不分段了吧~。程式碼如下:
public class Solution {
public boolean isAdditiveNumber(String num) {
int len = num.length();
int valid = len/2;
for(int i = 1; i <= valid; i++){
for(int j = 1; j <= valid; j++){
if((len - i - j) >= Math.max(i, j)){
if(check(num,num.substring(0, i),num.substring(i, i + j))){
return true;
}else{
continue;
}
}else{
break;
}
}
}
return false;
}
private boolean check(String num, String first, String second){
long addFir = Long.parseLong(first);
long addSec = Long.parseLong(second);
long addThi = addFir + addSec;
StringBuilder str = new StringBuilder("");
str.append(addFir).append(addSec).append(addThi);
while(num.startsWith(str.toString())){
if(num.length() == str.length()){
return true;
}
addFir = addSec;
addSec = addThi;
addThi = addFir + addSec;
str = str.append(addThi);
}
return false;
}
}