-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathadd-binary.cpp
More file actions
59 lines (51 loc) · 1 KB
/
add-binary.cpp
File metadata and controls
59 lines (51 loc) · 1 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "leetcode.h"
class Solution {
public:
string addBinary(string a, string b) {
int carry = 0;
// always assume a is longer
if (a.size() < b. size())
swap(a, b);
string result;
int p = a.size() - 1, q = b.size() - 1;
for (; q >= 0; p--, q--) {
int ap = a[p] - '0';
int bq = b[q] - '0';
int sum = ap ^ bq ^ carry;
result.push_back(sum + '0');
carry = (ap & bq) | (carry & (ap ^ bq));
}
while (p >= 0) {
int ap = a[p] - '0';
int sum = ap ^ carry;
result.push_back(sum + '0');
carry = ap & carry;
--p;
}
if (carry)
result.push_back('1');
std::reverse(result.begin(), result.end());
return result;
}
};
int main() {
Solution sol;
vector<string> a = {
"111111",
"0",
"1",
"1",
"101",
};
vector<string> b = {
"11",
"0",
"0",
"1",
"1"
};
for (int i = 0; i < a.size(); ++i) {
cout << sol.addBinary(a[i], b[i]) << '\n';
}
return 0;
}