0%

415. Add Strings

O(m+n) time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string addStrings(string num1, string num2) {
string res;
for (int i = num1.length() - 1, j = num2.length() - 1, c = 0;
i >= 0 || j >= 0 || c > 0;
--i, --j) {
int a = i < 0 ? 0 : (num1[i] - '0');
int b = j < 0 ? 0 : (num2[j] - '0');
int s = a + b + c;
res += '0' + s % 10;
c = s / 10;
}
return string(rbegin(res), rend(res));
}
};