-
Notifications
You must be signed in to change notification settings - Fork 0
/
201. Bitwise AND of Numbers Range.cpp
66 lines (54 loc) · 1.11 KB
/
201. Bitwise AND of Numbers Range.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
58
59
60
61
62
63
64
65
66
/*
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
Solution one using mask
Solution two shift m, n, until they are equal
Solution three is recursive
Solution four using n & ( n - 1 )
*/
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
if ( m == 0 ) return 0;
unsigned int d = 0x7fffffff;
while ((m & d) != (n & d)) {
d <<= 1;
}
return m & d;
}
};
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
if ( m == 0 || n == 0 ) return 0;
int i = 0;
while ( m != n )
{
m >>= 1;
n >>= 1;
i++;
}
return m << i;
}
};
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
return (n > m) ? (rangeBitwiseAnd(m / 2, n / 2) << 1) : m;
}
};
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
while ( n > m )
{
n = n & ( n - 1 );
}
return n;
}
};