Given two non-negative numbers num1 and num2 represented
as string, return the sum of num1 and num2.
Note:
- The length of both
num1andnum2is < 5100. - Both
num1andnum2contains only digits0-9. - Both
num1andnum2does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
class Solution {
public:
string addStrings(string num1, string num2) {
int len1 = num1.size();
int len2 = num2.size();
int len = max(len1, len2);
string result(len, '0');
int carry = 0;
while (len > 0) {
int sum = carry;
if (len1 > 0) {
sum += num1[--len1] - '0';
}
if (len2 > 0) {
sum += num2[--len2] - '0';
}
result[--len] = sum % 10 + '0';
carry = sum / 10;
}
return carry == 0? result: '1' + result;
}
};
本文介绍了一种不使用内置大数库或直接转换为整数的方法来实现两个以字符串形式给出的非负数的相加操作。通过逐位相加并处理进位的方式,实现了对长度可达5100的大数进行高效加法运算。
798

被折叠的 条评论
为什么被折叠?



