问题
思路
大整数加法实现。
代码
class Solution {
public:
string addStrings(string num1, string num2) {
reverse(num1);
reverse(num2);
std::string ret;
int sz1 = num1.size();
int sz2 = num2.size();
int i = 0;
int c = 0;
while(i < sz1 && i < sz2){
int tmp = num1[i] + num2[i] - 2*'0' + c;
ret = std::string(1, '0'+tmp%10) + ret;
c = tmp/10;
++i;
}
while(i < sz1){
int tmp = num1[i] + c - '0';
ret = std::string(1, '0'+tmp%10) + ret;
c = tmp/10;
++i;
}
while(i < sz2 ){
int tmp = num2[i] + c - '0';
ret = std::string(1, '0'+tmp%10) + ret;
c = tmp/10;
++i;
}
if(c) ret = std::string(1, '0'+c) + ret;
return ret;
}
private:
void reverse(std::string& nums){
int sz = nums.size();
int mid = nums.size()/2;
for(int i = 0; i < mid; ++i){
int t = nums[i];
nums[i] = nums[sz-1-i];
nums[sz-1-i] = t;
}
return;
}
};