Given two non-negative integers num1
and num2
represented
as string, return the sum of num1
and num2
.
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"
思路:把长度短的字符串用0补齐位数,从最后一位开始借位相加,反转即可。
分析:"123"和"045"
public class Solution {
/**
* @param num1 a non-negative integers
* @param num2 a non-negative integers
* @return return sum of num1 and num2
*/
public String addStrings(String num1, String num2) {
StringBuffer sb=new StringBuffer();
int len=Math.max(num1.length(),num2.length());
int carry=0;
for(int i=len-1;i>=0;i--){
if(num1.length()<num2.length()){
for(int j=num1.length();j<num2.length();j++){
num1="0"+num1;
}
}
if(num1.length()>num2.length()){
for(int j=num2.length();j<num1.length();j++){
num2="0"+num2;
}
}
char c1=num1.charAt(i);
char c2=num2.charAt(i);
int digit=(carry+(c1-'0')+(c2-'0'))%10;
sb.append(digit);
carry=(carry+(c1-'0')+(c2-'0'))/10;
}
if(carry!=0){
sb.append(carry);
}
return sb.reverse().toString();
}
}
第二遍
public class Solution {
/**
* @param num1 a non-negative integers
* @param num2 a non-negative integers
* @return return sum of num1 and num2
*/
public String addStrings(String num1, String num2) {
int diff=Math.abs(num1.length()-num2.length());
if(num1.length()>num2.length()){
for(int i=0;i<diff;i++){
num2="0"+num2;
}
}else{
for(int i=0;i<diff;i++){
num1="0"+num1;
}
}
String result="";
int carry=0;
for(int i=num1.length()-1;i>=0;i--){
int sum=carry+(num1.charAt(i)-'0')+(num2.charAt(i)-'0'); //要注意charAt之后要-'0'
int digit=sum%10;
result+=digit;
carry=sum/10;
}
if(carry!=0){
result+=carry;
}
return new StringBuffer(result).reverse().toString();
}
}