- 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.
public String addStrings(String num1, String num2) {
int m = num1.length(), n = num2.length();
if(m == 0) return num2;
if(n == 0) return num1;
char[] ans = new char[Math.max(m,n)+1];
int carry = 0;
int i = m-1, j = n-1, k = Math.max(m,n);
for(; i >=0 || j>=0 || carry!=0;i--,j--){
int sum = (i>=0? num1.charAt(i)- '0':0) + (j>=0? num2.charAt(j)- '0' :0) + carry;
ans[k--] =(char)(sum%10+'0');
carry = sum/10;
}
String s = "";
while(++k<Math.max(m,n)+1){
s+=ans[k];
}
return s;
}
没有评论:
发表评论