forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths1.cpp
More file actions
21 lines (21 loc) · 625 Bytes
/
s1.cpp
File metadata and controls
21 lines (21 loc) · 625 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// OJ: https://leetcode.com/problems/add-strings/
// Author: github.com/lzl124631x
// Time: O(MN)
// Space: O(1)
class Solution {
public:
string addStrings(string num1, string num2) {
string sum;
int carry = 0;
auto i1 = num1.rbegin(), i2 = num2.rbegin();
while (i1 != num1.rend() || i2 != num2.rend() || carry) {
int n = carry;
if (i1 != num1.rend()) n += *i1++ - '0';
if (i2 != num2.rend()) n += *i2++ - '0';
carry = n / 10;
sum += (n % 10) + '0';
}
reverse(sum.begin(), sum.end());
return sum;
}
};