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.
class Solution {
public:
string addStrings(string num1, string num2) {
int max_len = max(num1.size(), num2.size());
num1.insert(num1.begin(), max_len-num1.size(), '0');
num2.insert(num2.begin(), max_len-num2.size(), '0');
int t1=0, t2;
string ans;
for(int i=max_len-1; i>=0; i--){
int t = t1;
t1 =( (num1[i] - '0') + (num2[i] - '0') +t )/10;
t2 =( (num1[i] - '0') + (num2[i] - '0') +t )%10;
ans.insert(ans.begin(), 1, '0'+t2);
}
if(t1!=0)
ans.insert(ans.begin(), 1, '0'+t1);
return ans;
}
};