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?
How would you handle overflow for very large input integers?
Solution:
To handle large input integers, I use string addition to avoid overflow.
The idea is iterate all possible starting two numbers, return true as soon as we find the current number is an additive number.
eg, "199100199"
The possible starting two numbers includes:
[1,9],[1,99],[1,991],[1,9910],[1,99100],[1,991001],[1,9910019],[1,99100199],
[19,9],[19,91],[19,910],[19,9100],[19,91001],[19,910019],[19,9100199]....
Actually, when we tried [1,99] we will get an additive number and return true immediately.
public boolean isAdditiveNumber(String num) {
if(num==null || num.length()<3) return false;
for(int i=1; i<num.length();i++){
for(int j=i+1;j<num.length();j++){
String num1=num.substring(0,i);
String num2=num.substring(i,j);
String sum=addition(num1,num2);
int k=j;
while(k+sum.length()<=num.length() && num.substring(k,k+sum.length()).equals(sum)){
k=k+sum.length();
if(k==num.length()) return true;
num1=num2;
num2=sum;
sum=addition(num1,num2);
}
if(num.charAt(i)=='0') break;
}
if(num.charAt(0)=='0') break;
}
return false;
}
public String addition(String num1, String num2){
int l=Math.max(num1.length(),num2.length());
StringBuilder sb=new StringBuilder();
int carry=0;
for(int i=1;i<=l;i++){
int a=(num1.length()-i<0)? 0: num1.charAt(num1.length()-i)-'0';
int b=(num2.length()-i<0)? 0: num2.charAt(num2.length()-i)-'0';
int sum=a+b+carry;
sb.append(sum%10);
carry=sum/10;
}
if(carry!=0) sb.append(1);
return sb.reverse().toString();
}
No comments:
Post a Comment