难度简单137
给定两个字符串形式的非负整数 num1
和num2
,计算它们的和。
注意:
num1
和num2
的长度都小于 5100.num1
和num2
都只包含数字0-9
.num1
和num2
都不包含任何前导零。- 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
class Solution {
public:
string addStrings(string num1, string num2) {
int i = num1.length() - 1;
int j = num2.length() - 1;
int carry = 0,a = 0,b = 0,save = 0;
string res;
char mid;
while(i >= 0 || j >=0)
{
if(i >= 0)
{
a = num1[i] - '0';
i--;
}
else
a = 0;
if(j >= 0)
{
b = num2[j] - '0';
j--;
}
else
b = 0;
save = a + b + carry;
if(save > 9)
{
carry = 1;
mid= '0' + save%10;
res = mid + res;
}
else
{
carry = 0;
mid= '0' + save;
res = mid + res;
}
}
if(carry == 1)
return '1' + res;
else
return res;
}
};