Given two non-negative numbers num1 and num2 represented
as string, return the sum of num1 and num2.
Note:
- The length of both
num1andnum2is < 5100. - Both
num1andnum2contains only digits0-9. - Both
num1andnum2does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
public class Solution {
public static String addStrings(String num1, String num2)
{
int len1=num1.length();
int len2=num2.length();
int carry=0;
int minlen=Math.min(len1, len2);
int cnt=0;
StringBuilder sb=new StringBuilder();
int i,j;
for(i=len1-1,j=len2-1;cnt<minlen;i--,j--,cnt++)
{
int sum=(num1.charAt(i)-'0')+(num2.charAt(j)-'0')+carry;
carry=sum/10;
sum=sum%10;
sb.append(sum);
}
if(len1>=len2)
for(;i>=0;i--)
{
int sum=num1.charAt(i)-'0'+carry;
carry=sum/10;
sum%=10;
sb.append(sum);
}
else {
for(;j>=0;j--)
{
int sum=num2.charAt(j)-'0'+carry;
carry=sum/10;
sum%=10;
sb.append(sum);
}
}
if(carry>0)
sb.append(carry);
return sb.reverse().toString();
}
}
3026



被折叠的 条评论
为什么被折叠?



