Given two non-negative numbers 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.
这个题目相对比较简单,思路是先将两个字符串翻转,然后就可以从字符串0至len-1位相加,然后将结果翻转
主要的注意事项是,不要漏掉最高位的可能进位,直接看代码吧,应该更容易明白!
【AC代码】
class Solution {
public:
string addStrings(string num1, string num2) {
std::string res;
int len1 = num1.size();
int len2 = num2.size();
if (len1 == 0 && len2 == 0)
return res;
if (len1 == 0 && len2 != 0)
return num2;
if (len1 != 0 && len2 == 0)
return num1;
num1 = strReverse(num1);
num2 = strReverse(num2);
int flag = 0;
int i = 0;
for (i = 0; i < len1 && i < len2; ++i) {
res += (num1[i] - '0' + num2[i] - '0' + flag) % 10 + '0';
flag = (num1[i] - '0' + num2[i] - '0' + flag) / 10;
}
while (i < len1) {
res += (num1[i] - '0' + flag) % 10 + '0';
flag = (num1[i] - '0' + flag) / 10;
++i;
}
while (i < len2) {
res += (num2[i] - '0' + flag) % 10 + '0';
flag = (num2[i] - '0' + flag) / 10;
++i;
}
if (flag > 0) {
res += flag + '0';
}
res = strReverse(res);
return res;
}
std::string strReverse(const std::string& num) {
int len = num.size();
std::string str;
str.resize(len);
for (int i = 0; i < len; ++i) {
str[i] = num[len - 1 - i];
}
return str;
}
};