415. Add Strings*
https://leetcode.com/problems/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.
C++ 实现 1
使用 carry_over
. 这种类型的题在 LeetCode 中出现过很多次, 总会以不同的面目出现, 比如链表啥的.
class Solution {
public:
string addStrings(string num1, string num2) {
int carry_over = 0;
int i = num1.size() - 1, j = num2.size() - 1;
string res;
while (i >= 0 || j >= 0 || carry_over) {
int n1 = i >= 0 ? num1[i] - '0' : 0;
int n2 = j >= 0 ? num2[j] - '0' : 0;
int sum = n1 + n2 + carry_over;
res += std::to_string(sum % 10);
carry_over = sum / 10;
i --;
j --;
}
std::reverse(res.begin(), res.end());
return res;
}
};