Description
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
My solution
基本想法是一个carry保存进位信息, x = x1+x2+carry
. 需要注意的是, num1和num2长度不同, 计算完毕重合部分的加法要把较长的num长出的部分添加到最后结果上. 而由于carry可能!=0, 所以长出来的部分也要进行一次大数加法. 另外, 哪个数是真正的size更大的数呢? 或者每次判断, 或者直接令num1是长的, num2是短的, 如果swap,需要开辟一个temp的空间. 如果不允许改变num1和num2, 则要开辟两个str的空间. 进而考虑到, 即使短的num2没有值参与运算了, 也让x2='0'参与加减法, 这样子就可以把多出来的部分需要进行的额外的大数加法融合在了相同的循环结构里. carry最后一个值的问题可以在最后修正. 故有如下代码:
class Solution {
public:
string addStrings(string num1, string num2) {
string res;
char c = 0;
char x1, x2, x;
for (int i = num1.size() - 1, j = num2.size() - 1; i > -1 || j > -1; --i, --j) {
x1 = i > -1 ? num1[i] : '0';
x2 = j > -1 ? num2[j] : '0';
x = x1 - '0' + x2 - '0' + c;
c = char(x / 10);
x %= 10;
res = char(x + '0') + res;
}
res = c > 0 ? '1' + res : res;
return res;
}
};
上述code一次AC, 查看discuss优秀方案, 和我的思路相近, 有可借鉴的地方, 比如最后的修正carry可以融入循环里面,代码更美一些.
Discuss
class Solution {
public:
string addStrings(string num1, string num2) {
int i = num1.size() - 1;
int j = num2.size() - 1;
int carry = 0;
string res = "";
while(i>=0 || j>=0 || carry){
long sum = 0;
if(i >= 0){sum += (num1[i] - '0');i--;}
if(j >= 0){sum += (num2[j] - '0');j--;}
sum += carry;
carry = sum / 10;
sum = sum % 10;
res = res + to_string(sum);
}
reverse(res.begin(), res.end());
return res;
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。