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.
class Solution {
public:
string addStrings(string num1, string num2) {
int len1 = num1.size();
int len2 = num2.size();
int len = max(len1, len2);
string result(len, '0');
int carry = 0;
while (len > 0) {
int sum = carry;
if (len1 > 0) {
sum += num1[--len1] - '0';
}
if (len2 > 0) {
sum += num2[--len2] - '0';
}
result[--len] = sum % 10 + '0';
carry = sum / 10;
}
return carry == 0? result: '1' + result;
}
};