题目链接
思路:
- 比较简单的模拟题,判断出哪一个字符串为较长字符串,然后再将短字符串和长字符串一位一位的相加,同时记录进位
代码:
class Solution {
public:
string addStrings(string num1, string num2) {
string a,b;
int pos=0;
if(num1.size()>=num2.size())
{
a=num1;
b=num2;
}
if(num1.size()<num2.size())
{
a=num2;
b=num1;
}
int l1=a.size()-1,l2=b.size()-1;
while(l2>=0)
{
int temp=a[l1]-'0'+b[l2]-'0'+pos;
pos=temp/10;
temp%=10;
a[l1]=temp+'0';
l1--;
l2--;
}
while(l1>=0)
{
int temp=a[l1]-'0'+pos;
pos=temp/10;
temp%=10;
a[l1]=temp+'0';
l1--;
}
if(pos>0)
{
string temp=to_string(pos);
a=temp+a;
}
return a;
}
};