Given two non-negative numbers num1
and num2
represented
as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
先将num1和num2翻转,最后再将ans翻转。需注意最后可能需要加上进位。
class Solution {
public:
string addStrings(string num1, string num2) {
string ans = "";
int flag = 0;
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int dig1 = 0, dig2 = 0;
auto it1 = num1.begin(), it2 = num2.begin();
while (it1 != num1.end() && it2 != num2.end()) {
int tmp = *it1 - '0' + *it2 - '0' + flag;
flag = tmp / 10;
tmp %= 10;
ans.push_back(tmp + '0');
++it1, ++it2;
}
while (it1 != num1.end()) {
int tmp = *it1 - '0' + flag;
flag = tmp / 10;
tmp %= 10;
ans.push_back(tmp + '0');
++it1;
}
while (it2 != num2.end()) {
int tmp = *it2 - '0' + flag;
flag = tmp / 10;
tmp %= 10;
ans.push_back(tmp + '0');
++it2;
}
if (flag == 1)
ans += '1';
reverse(ans.begin(), ans.end());
return ans;
}
};