模拟加法处理过程,由于两数相加是从右往左进位,这里需要将两个字符串先反转之后,再进行逐位相加处理
class Solution {
public:
string addStrings(string num1, string num2) {
string ans;
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int n = max(num1.size(), num2.size()), carry = 0;
for (int i = 0; i < n; ++i) {
carry += i < num1.size() ? (num1.at(i) - '0') : 0;
carry += i < num2.size() ? (num2.at(i) - '0') : 0;
ans.push_back('0' + (carry % 10));
carry /= 10;
}
if (carry) {
ans.push_back('1');
}
reverse(ans.begin(), ans.end());
return ans;
}
};