原文题目:

447. Add Strings

解题:

字符串的当做整数来做加法,其实就是大数加法的简化版本

思路:

1)考虑不同位数,如"1234"+“45”,需要先处理低两位,再处理num1的高两位

2)考虑进位,相加大于10时就要进位,进位值 = sum/10;

3)考虑最高位的进位,如“5099”+“4987”最后得到了五位的“10086”

AC代码:

class Solution {
public:
string addStrings(string num1, string num2)
{
string re = "";
int len1 = num1.length();
int len2 = num2.length();
int temp1,temp2,tempsum = 0;
string tempstr;
int carry = 0;
int i = 0;
//计算相同位的低位,同时保存进位到carry
while(len1&&len2)
{
temp1 = num1[len1-1]-'0';
temp2 = num2[len2-1]-'0';
tempsum = temp1 + temp2 + carry;
carry = tempsum / 10;
tempstr = tempsum%10 + '0';
re = tempstr + re; //注意re在后,若为re += tempstr,那么结果就需要翻转了
len1--;
len2--;
}
//计算num1或者num2剩余的位
if(len1)
{
for(i = len1-1;i>=0;i--)
{
tempsum = num1[i]-'0' +carry;
carry = tempsum / 10;
tempstr = tempsum%10 + '0';
re = tempstr + re;
}
}
if(len2)
{
for(i = len2-1;i>=0;i--)
{
tempsum = num2[i]-'0' +carry;
carry = tempsum / 10;
tempstr = tempsum%10 + '0';
re = tempstr + re;
}
}
//剩余的位中如果还有进位,那么还需要加上
if(carry)
{
tempstr = carry+'0';
re = tempstr +re;
}
return re;
}
};

  

05-11 13:01