给定两个字符串形式的非负整数 num1
和num2
,计算它们的和。
提示:
num1
和num2
的长度都小于 5100num1
和num2
都只包含数字0-9
num1
和num2
都不包含任何前导零- 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式
class Solution {
public:
string addStrings(string num1, string num2) {
int N1 = num1.length();
int N2 = num2.length();
int index1 = N1-1;
int index2 = N2-1;
string res = "";
int t = 0;
while(index1>=0 && index2>=0){
int temp = (num1[index1--]-'0')+(num2[index2--]-'0');
res += (temp+t)%10+'0';
t = (temp+t)/10;
}
if(index1<0){
while(index2>=0){
int temp = (num2[index2--]-'0');
res += (temp+t)%10+'0';
t = (temp+t)/10;
}
}else{
while(index1>=0){
int temp = (num1[index1--]-'0');
res += (temp+t)%10+'0';
t = (temp+t)/10;
}
}
if(t!=0)
res += 1+'0';
reverse(res.begin(),res.end());
return res;
}
};