-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path67.cpp
More file actions
31 lines (31 loc) · 828 Bytes
/
67.cpp
File metadata and controls
31 lines (31 loc) · 828 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
class Solution {
public:
string addBinary(string a, string b) {
string out;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int idxA = 0;
int idxB = 0;
int carry = 0;
int current = 0;
while (idxA < a.size() || idxB < b.size()) {
current = carry;
if (idxA < a.size()) {
current += a[idxA] - '0';
idxA++;
}
if (idxB < b.size()) {
current += b[idxB] - '0';
idxB++;
}
out.push_back(current % 2 + '0');
carry = current / 2;
}
while (carry) {
out.push_back(carry % 2 + '0');
carry /= 2;
}
reverse(out.begin(), out.end());
return out;
}
};