//此题实际上是模拟加法器实现的原理
class Solution {
public:
string addStrings(string num1, string num2) {
int end1 = num1.size() -1, end2 = num2.size()-1;
string retstr;
//进位
int next = 0;
while(end1>= 0 || end2>= 0)
{
int val1 = 0;
if(end1 >= 0)
{
val1 = num1[end1] - '0';
end1--;
}
int val2 = 0;
if(end2 >= 0)
{
val2 = num2[end2] - '0';
end2--;
}
int ret = val1 + val2 + next;
if(ret > 9)
{
ret -= 10;
next =1;
}
else
{
next = 0;
}
//retstr.insert(retstr.begin(), 1, '0'+ret);//时间复杂度为O(N^2),头插需要挪动数据
retstr += ('0' + ret);
}
if(next == 1)
//retstr.insert(0, 1, '1');
retstr += ('1');
reverse(retstr.begin(), retstr.end());//可以换成尾插再逆置一下
return retstr;
}
};