415. Add Strings
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Example 1:
Input: num1 = “11”, num2 = “123”
Output: “134”
Example 2:
Input: num1 = “456”, num2 = “77”
Output: “533”
Example 3:
Input: num1 = “0”, num2 = “0”
Output: “0”
Constraints:
1 <= num1.length, num2.length <= 104
num1 and num2 consist of only digits.
num1 and num2 don’t have any leading zeros except for the zero itself.
solution1模拟
class Solution {
public:
string addStrings(string num1, string num2) {
int i = num1.length() - 1, j = num2.length() - 1, add = 0;
string ans = "";
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1[i] - '0' : 0;
int y = j >= 0 ? num2[j] - '0' : 0;
int result = x + y + add;
ans.push_back('0' + result % 10);
add = result / 10;
i -= 1;
j -= 1;
}
// 计算完以后的答案需要翻转过来
reverse(ans.begin(), ans.end());
return ans;
}
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/add-strings/solution/zi-fu-chuan-xiang-jia-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
solution2 字符串+双指针
先在num1或num2头部用0补齐,然后同时从num1、num2尾部向前遍历逐位相加(加上进位)。num1当前位更新为和的余数,和除以10为进位值。遍历结束后,进位为1,则在头部补上1。
class Solution {
public:
string addStrings(string num1, string num2) {
int n=num1.size(), m=num2.size(), c=0; // c表示进位
if(n < m) // num1短,在num1前补齐0
num1 = string(m-n, '0') + num1;
else // num2短,在num2前补齐0
num2 = string(n-m, '0') + num2;
for(int i=max(n,m)-1;i>=0;i--){ // 从后向前逐位遍历num1和num2
int s = (num1[i]-'0') + (num2[i]-'0') + c; // 当前位的和
num1[i] = '0' + s%10; // 更改num1当前位
c = s / 10; // 进位计算
}
return c ? "1"+num1 : num1; // 最后还有进位,则在num1前补上1
}
};
作者:nbgao
链接:https://leetcode.cn/problems/add-strings/solution/nbgao-415-zi-fu-chuan-xiang-jia-by-nbgao-a9nx/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。