思路:每个字符串一个指针
tips:注意res=最新的结果+res,不用最后再反转
class Solution {
public:
string addStrings(string num1, string num2) {
//大数相加
int l1=num1.size(),l2=num2.size();
int p1=l1-1,p2=l2-1;
int carry=0;
string res="";
int i=0;
while(p1>=0 || p2>=0 || carry!=0)
{
if(p1<0 && p2<0)
{
res=to_string(carry)+res;
carry=0;
break;
}
else if(p1<0)
{
while(p2>=0)
{
res=to_string((num2[p2]-'0'+carry)%10)+res;
carry=(num2[p2]-'0'+carry)/10;
i++;
p2--;
}
}
else if(p2<0)
{
while(p1>=0)
{
res=to_string((num1[p1]-'0'+carry)%10)+res;
carry=(num1[p1]-'0'+carry)/10;
i++;
p1--;
}
}
else
{
res=to_string((num1[p1]-'0'+num2[p2]-'0'+carry)%10)+res;
carry=(num1[p1]-'0'+num2[p2]-'0'+carry)/10;
p1--;
p2--;
i++;
}
}
return res;
}
};