这题其实写起来有点烦的 注意index不要超,使用i作count会比较方便。
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int len1 = num1.length();
int len2 = num2.length();
int longer = len1>len2?len1:len2;
int shorter = longer==len1? len2:len1;
int carry = 0;
// use i for count not index
for(int i = 0;i<shorter;i++)
{
int n1 = (int)(num1.charAt(len1-1-i)-'0');
int n2 = (int)(num2.charAt(len2-1-i)-'0');
int num = (n1+n2+carry)%10;
carry=(n1+n2+carry)/10;
sb.insert(0,num);
}
for(int i = 0;i<longer-shorter;i++)
{
if(len1==longer)
{
int n1 = (int)(num1.charAt(len1-shorter-1-i)-'0');
int num = (n1+carry)%10;
carry=(n1+carry)/10;
System.out.println(num);
sb.insert(0,num);
}
else
{
int n2 = (int)(num2.charAt(len2-shorter-1-i)-'0');
int num = (n2+carry)%10;
carry=(n2+carry)/10;
sb.insert(0,num);
}
}
if(carry==1)
sb.insert(0,1);
return sb.toString();
}
}