Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is< 5100
. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
题意:实现字符串的加法。
思路1:将两个字符串翻转,低位左对齐,然后一一相加即可。和第二题 2. Add Two Numbers
一样的做法。以前写的大(中型?)整数类就是这样加的。
代码:
class Solution {
public:
string addStrings(string num1, string num2) {
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
string ans;
int n = num1.size(), m = num2.size(), i, c = 0;
for (i = 0; i < n || i < m; ++i) {
int t = c;
if (i < n) t += (num1[i] - '0');
if (i < m) t += (num2[i] - '0');
c = t / 10;
ans += char(t % 10 + '0');
}
if (c) ans += char(c + '0');
reverse(ans.begin(), ans.end());
return ans;
}
};
效率:
执行用时:4 ms, 在所有 C++ 提交中击败了94.90% 的用户
内存消耗:6.7 MB, 在所有 C++ 提交中击败了84.04% 的用户
思路2:不过上面还是啰嗦了一点,可以不对原串翻转,还可以在循环中就处理掉多余的进位。
代码:
class Solution {
public:
string addStrings(string num1, string num2) {
string ans;
int i = num1.size() - 1, j = num2.size() - 1, c = 0;
while (i >= 0 || j >= 0 || c != 0) {
if (i >= 0) c += (num1[i--] - '0');
if (j >= 0) c += (num2[j--] - '0');
ans += char(c % 10 + '0');
c /= 10;
}
reverse(ans.begin(), ans.end());
return ans;
}
};