-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
49 lines (44 loc) · 1.24 KB
/
main.cpp
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
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string result;
for (int i = 0; i < a.size() || i < b.size(); ++i) {
int v = 0;
if (i < result.size()) {
++v;
} else {
result += '0';
}
if (i < a.size() && a[i] == '1') ++v;
if (i < b.size() && b[i] == '1') ++v;
if (v == 1) {
result[i] = '1';
} else if (v == 2) {
result[i] = '0';
result += '1';
} else if (v == 3) {
result[i] = '1';
result += '1';
}
}
return {result.rbegin(), result.rend()};
}
};
class Solution {
public:
string addBinary(string a, string b) {
int i = a.size() - 1;
int j = b.size() - 1;
string result;
int carry = 0;
while (i >= 0 || j >= 0 || carry) {
if (i >= 0) carry += a[i--] == '1';
if (j >= 0) carry += b[j--] == '1';
result += to_string(carry & 1);
carry >>= 1;
}
return {result.rbegin(), result.rend()};
}
};