Given two non-negative integers 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.
Companies:
Facebook, Microsoft
Related Topics:
Math
Similar Questions:
// OJ: https://leetcode.com/problems/add-strings/
// Author: github.com/lzl124631x
// Time: O(MN)
// Space: O(1)
class Solution {
public:
string addStrings(string num1, string num2) {
string sum;
int carry = 0;
auto i1 = num1.rbegin(), i2 = num2.rbegin();
while (i1 != num1.rend() || i2 != num2.rend() || carry) {
int n = carry;
if (i1 != num1.rend()) n += *i1++ - '0';
if (i2 != num2.rend()) n += *i2++ - '0';
carry = n / 10;
sum += (n % 10) + '0';
}
reverse(sum.begin(), sum.end());
return sum;
}
};