Leetcode415. Add Strings
题目
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.
解题分析
这道题乍一看第一想法就是将两个数转成十进制数,然后将两个数相加之后再转成字符串,但是这样的话很容易出现当数字很大的时候求和溢出的情况,进而得不到正确的结果。所以我们就只能另辟蹊径了。
我们可以模拟加法竖式计算的过程,用变量carry来记录进位的情况,从最末位开始相加,如果出现进位,就用carry来记录进位的数字,最后只需再判断一下首位相加是否出现进位的情况就可以了,问题就顺利地得到了解决~
源代码
class Solution {
public:
string addStrings(string num1, string num2) {
int number1 = 0, number2 = 0, size, size1 = num1.size(), size2 = num2.size(), number, carry = 0;
string s = "";
char c;
if (size1 > size2) {
for (int i = 0; i < size1 - size2; i++) {
num2 = '0' + num2;
}
size = size1;
}
else if (size1 < size2) {
for (int i = 0; i < size2 - size1; i++) {
num1 = '0' + num1;
}
size = size2;
}
for (int i = size - 1; i >= 0; i--) {
int bit = num1[i] - '0' + num2[i] - '0' + carry;
if (bit < 10) {
c = bit + '0';
carry = 0;
}
else {
c = bit % 10 + '0';
carry = bit / 10;
}
s = c + s;
}
if (carry != 0) {
c = carry + '0';
s = c + s;
}
return s;
}
};
以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~