-
Notifications
You must be signed in to change notification settings - Fork 0
/
0307.cpp
57 lines (54 loc) · 1.15 KB
/
0307.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
50
51
52
53
54
55
56
57
#include <iostream>
#include <cstdio>
#include <cstdlib>
#define BITSIZE 4
int indexFirstZeroAfterOne(int num) {
int cur = 1;
int result;
int i = 0;
int counter = 0;
int mask = ~0;
int allOnes = ~0;
while (!(cur & num)) {
cur = cur << 1;
i++;
}
while ((cur & num) && (i < BITSIZE * sizeof(int))) {
cur = cur << 1;
// Number of 1;
counter++;
i++;
}
// Now i is the index of first 0 after 1 turn it on
// and turn this bit on.
mask -= (cur - 1);
int tmp = mask & num;
std::cout << tmp << " " << cur << " " << ~(allOnes << (counter - 1)) << std::endl;
result = (mask & num) + cur + (~(allOnes << (counter-1)));
std::cout << result << std::endl;
return result;
}
/* TODO the smallest one
int indexFirstOneAfterZero(int num) {
int cur = 1;
int i;
int counter = 0;
int mask = ~0;
while ((cur & num)) {
cur = cur << 1;
i++;
}
while (!(cur & num) && (i < BITSIZE * sizeof(int))) {
cur = cur << 1;
// Number of zeros;
counter++;
i++;
}
mask -= ((cur << 1)- 1);
}
*/
int main() {
int n = 44;
std::cout << n << " " << indexFirstZeroAfterOne(n) << std::endl;
return 0;
}