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.
分析:
将两个用字符串表示的非负整数相加,返回和的字符串,不能直接使用库函数。从num1和num2尾部开始依次取出数字与进位相加,用carry表示进位,每步求和结果从开始处依次插入res中。加到最后时判断进位是否为1,若是,在res前补“1”即可。
class Solution {
public:
string addStrings(string num1, string num2) {
int len1 = num1.size();
int len2 = num2.size();
int carry = 0;
int i = len1-1;
int j = len2-1;
string res = "";
while(i>=0 || j>=0)
{
int a = 0;
int b = 0;
if(i >= 0)
a = num1[i] - '0';
else
a = 0;
if(j >= 0)
b = num2[j] - '0';
else
b = 0;
i--;
j--;
int sum = a + b + carry;
res.insert(res.begin() , sum%10+'0');
carry = sum/10;
}
if(carry == 1)
return "1" + res;
else
return res;
}
};