8000 2 · javasharper/leetcode@1eff33d · GitHub
[go: up one dir, main page]

Skip to content

Commit 1eff33d

Browse files
committed
2
1 parent c8b66d4 commit 1eff33d

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

AddBinary/AddBinary.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public:
3+
string addBinary(string a, string b) {
4+
// Start typing your C/C++ solution below
5+
// DO NOT write int main() function
6+
7+
string c;
8+
int len_a = a.size();
9+
int len_b = b.size();
10+
int carry = 0;
11+
for (int i = 0; i < min(len_a, len_b); i++) {
12+
int x = a[len_a - i - 1] - '0';
13+
int y = b[len_b - i - 1] - '0';
14+
c += (x + y + carry) % 2 + '0';
15+
carry = (x + y + carry) / 2;
16+
}
17+
if (len_a > len_b) {
18+
for (int i = len_b; i < len_a; i++) {
19+
int x = a[len_a - i - 1] - '0';
20+
c += (x + carry) % 2 + '0';
21+
carry = (x + carry) / 2;
22+
}
23+
}
24+
else if (len_a < len_b) {
25+
for (int i = len_a; i < len_b; i++) {
26+
int x = b[len_b - i - 1] - '0';
27+
c += (x + carry) % 2 + '0';
28+
carry = (x + carry) / 2;
29+
}
30+
}
31+
while (carry) {
32+
c += carry % 2 + '0';
33+
carry /= 2;
34+
}
35+
reverse(c.begin(), c.end());
36+
return c;
37+
}
38+
};

0 commit comments

Comments
 (0)
0