forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd-binary_1_AC.cpp
More file actions
36 lines (34 loc) · 824 Bytes
/
Copy pathadd-binary_1_AC.cpp
File metadata and controls
36 lines (34 loc) · 824 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <algorithm>
using std::swap;
class Solution {
public:
string addBinary(string a, string b) {
if (a.size() > b.size()) {
swap(a, b);
}
int la = a.size();
int lb = b.size();
string c = "";
c.resize(lb + 1, 0);
int i;
for (i = 0; i < la; ++i) {
c[i] = a[la - 1 - i] - '0';
}
for (i = 0; i < lb; ++i) {
c[i] += b[lb - 1 - i] - '0';
}
for (i = 0; i < lb; ++i) {
c[i + 1] += c[i] / 2;
c[i] %= 2;
}
while (c.size() > 1 && c.back() == 0) {
c.pop_back();
}
int lc = c.size();
for (i = 0; i < lc; ++i) {
c[i] += '0';
}
reverse(c.begin(), c.end());
return c;
}
};