forked from sachuverma/DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10. Bitwise AND of Numbers Range.cpp
More file actions
60 lines (39 loc) · 986 Bytes
/
10. Bitwise AND of Numbers Range.cpp
File metadata and controls
60 lines (39 loc) · 986 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7
Output: 4
Example 2:
Input: left = 0, right = 0
Output: 0
Example 3:
Input: left = 1, right = 2147483647
Output: 0
Constraints:
0 <= left <= right <= 231 - 1
*/
class Solution {
public:
int pos(int x) {
int cnt = -1;
while(x) {
x>>=1;
cnt++;
}
return cnt;
}
int rangeBitwiseAnd(int l, int r) {
int res = 0;
while(l&&r) {
int p1 = pos(l);
int p2 = pos(r);
if(p1!=p2)
break;
int val = (int)pow(2,p1);
res+=val;
l = l-val;
r = r-val;
}
return res;
}
};