Skip to content

Commit 3588330

Browse files
authored
Create add-strings.cpp
1 parent e018cdc commit 3588330

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

C++/add-strings.cpp

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string addStrings(string num1, string num2) {
7+
string result;
8+
9+
for (int i = num1.size() - 1, j = num2.size() - 1, carry = 0;
10+
i >= 0 || j >= 0 || carry;
11+
carry /= 10) {
12+
13+
if (i >= 0) {
14+
carry += num1[i--] - '0';
15+
}
16+
if (j >= 0) {
17+
carry += num2[j--] - '0';
18+
}
19+
result += to_string(carry % 10);
20+
}
21+
reverse(result.begin(), result.end());
22+
23+
return result;
24+
}
25+
};

0 commit comments

Comments
 (0)