-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_gap.cpp
More file actions
39 lines (34 loc) · 747 Bytes
/
binary_gap.cpp
File metadata and controls
39 lines (34 loc) · 747 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
37
38
39
#include <iostream>
using namespace std;
int binary_gap(int n)
{
unsigned mask = (1u << 30);
bool one = false;
int bin_gap = 0;
int max_gap = 0;
while (mask) {
if (one) {
if ((n & mask) == 0) {
++bin_gap;
} else {
if (max_gap < bin_gap) {
max_gap = bin_gap;
}
bin_gap = 0;
}
} else {
one = (n & mask) != 0 ;
}
mask >>= 1;
}
return max_gap;
}
int main()
{
cout << binary_gap(9) << endl;
cout << binary_gap(529) << endl;
cout << binary_gap(20) << endl;
cout << binary_gap(15) << endl;
cout << binary_gap(32) << endl;
return 0;
}