Skip to content

Commit 0b0ee40

Browse files
committed
415. Add Strings
1 parent 15093a8 commit 0b0ee40

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

add-strings.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//Runtime: 12 ms
2+
class Solution {
3+
public:
4+
string addStrings(string num1, string num2) {
5+
int i = num1.size() - 1;
6+
int j = num2.size() - 1;
7+
int carry = 0;
8+
string res;
9+
while (i >= 0 || j >= 0) {
10+
int x = (i >= 0 ? num1[i] - '0' : 0) + (j >= 0 ? num2[j] - '0' : 0) + carry;
11+
carry = x / 10;
12+
res += (x % 10 + '0');
13+
i--; j--;
14+
}
15+
16+
if (carry != 0) {
17+
res += (carry + '0');
18+
}
19+
20+
reverse(res.begin(), res.end());
21+
return res;
22+
}
23+
};

0 commit comments

Comments
 (0)