LeetCode刷题实战415:字符串相加
共 2175字,需浏览 5分钟
·
2021-10-21 07:16
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
示例
示例 1:
输入:num1 = "11", num2 = "123"
输出:"134"
示例 2:
输入:num1 = "456", num2 = "77"
输出:"533"
示例 3:
输入:num1 = "0", num2 = "0"
输出:"0"
解题
class Solution {
public:
string addStrings(string num1, string num2) {
int i=num1.size()-1,j=num2.size()-1,carry=0;
string ans;
while(i>=0&&j>=0){
carry+=(num1[i]-'0')+(num2[j]-'0'); //从两个字符串的后面开始相加,记得加上进位
ans.push_back(carry%10+'0'); //将本位的求和结果放到结果中
carry/=10;
--i;--j;
}
while(i>=0){ //和下面的while,这两个只会执行其中的一个
carry+=(num1[i]-'0');
ans.push_back(carry%10+'0');
carry/=10;
--i;
}
while(j>=0){
carry+=(num2[j]-'0');
ans.push_back(carry%10+'0');
carry/=10;
--j;
}
while(carry!=0){ //最后记得处理可能不为0的carry
ans.push_back(carry%10+'0');
carry/=10;
}
reverse(ans.begin(),ans.end()); //将结果字符串进行翻转
return ans;
}
};