655.Big Integer Addition
1.Description(Easy)
Given two non-negative integersnum1
andnum2
represented as string, return the sum ofnum1
andnum2
.
Notice
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example
Given num1 ="123"
, num2 ="45"
return"168"
2.Code
乘法的答案在这里:http://www.jiuzhang.com/solutions/big-integer-multiplication/
跟167 Add two number基本一样,需要一个carry控制进位。
需要注意的是把char转换成int的时候要用num.charAt(i)-'0',而不能直接强制转换(int).
public String addStrings(String num1, String num2) {
if((num1==null ||num1.length()==0)&& (num2==null || num2.length()==0)){
return "";
}
if(num1==null ||num1.length()==0){
return num2;
}
if(num2==null || num2.length()==0){
return num1;
}
int carry=0;
StringBuilder result=new StringBuilder();
int i=num1.length()-1;
int j=num2.length()-1;
while(i>=0 && j>=0){
int sum=num1.charAt(i)-'0'+num2.charAt(j)-'0'+carry;
carry=sum/10;
int current=sum%10;
result.append(current);
i--;
j--;
}
while(i>=0){
int sum=num1.charAt(i)-'0'+carry;
carry=sum/10;
int current=sum%10;
result.append(current);
i--;
}
while(j>=0){
int sum=num2.charAt(j)-'0'+carry;
carry=sum/10;
int current=sum%10;
result.append(current);
j--;
}
if(carry!=0){
result.append(carry);
}
String res=result.reverse().toString();
return res;
}
Last updated
Was this helpful?