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.
class Solution {
public:
string addStrings(string num1, string num2) {
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
int sum=0,carry=0;
string ans="";
for(int i=0;i<num1.length()||i<num2.length();i++){
sum=carry;
if(i<num1.length()){
sum=sum+num1[i]-'0';
}
if(i<num2.length()){
sum=sum+num2[i]-'0';
}
ans=to_string(sum%10)+ans;
carry=sum/10;
}
if(carry){
ans=to_string(carry)+ans;
}
return ans;
}
};