-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path201.cpp
More file actions
26 lines (26 loc) · 691 Bytes
/
201.cpp
File metadata and controls
26 lines (26 loc) · 691 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
class Solution {
public:
vector<bool> num2bits(int num) {
vector<bool> bits(32, 0);
int index = 31;
while (num) {
bits[index] = num % 2;
num /= 2;
index--;
}
return bits;
}
int rangeBitwiseAnd(int left, int right) {
vector<bool> leftBits = num2bits(left);
vector<bool> rightBits = num2bits(right);
int res = 0;
for (int i = 0; i < 32; ++i) {
if (!leftBits[i] && !rightBits[i]) continue;
else if (leftBits[i] && rightBits[i]) {
res += (1 << (32 - i - 1));
}
else break;
}
return res;
}
};