【LeetCode】415. Add Strings,用string模拟加法
题目链接:https://leetcode.com/problems/add-strings/#/description
这个题的目的就是用string模拟整数加法
class Solution {
public:
string addStrings(string num1, string num2) {
reverse(num1.begin(),num1.end());//字符串逆序
reverse(num2.begin(),num2.end());
string res="";//加法结果保存在res字符串中
int flag = 0;//进位标志
string::iterator i,j;
i=num1.begin();
j=num2.begin();
char c;//保存中间结果
for(;i!=num1.end()&&j!=num2.end();i++,j++)
{
c = (flag + *i-'0'+*j-'0')%10+'0';
flag = (flag + *i-'0'+*j-'0')/10;
res+=c;
}
while(i!=num1.end())
{
c = (flag + *i-'0')%10+'0';
flag = (flag + *i-'0')/10;
res+=c;
i++;
}
while(j!=num2.end())
{
c = (flag + *j-'0')%10+'0';
flag = (flag + *j-'0')/10;
res+=c;
j++;
}
if(flag)
res+='1';
reverse(res.begin(),res.end());
return res;
}
};