Problem
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both num1 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution
class Solution {
public:
string addStrings(string num1, string num2) {
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
string ret = "";
int carry = 0;
for(int i = 0,j=0;i<num1.size() || j < num2.size() || carry;++i,++j)
{
int sum = (i<num1.size()?num1[i]-'0':0) + (j < num2.size()?num2[j] -'0':0) + carry;
int digit = sum % 10;
carry = sum / 10;
ret = to_string(digit) + ret;
}
return ret;
}
};