forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path201_Bitwise_AND_of_numbers_range
47 lines (43 loc) · 1021 Bytes
/
201_Bitwise_AND_of_numbers_range
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
// https://leetcode.com/problems/bitwise-and-of-numbers-range/
class Solution {
// BRIAN KERNIGHAN'S ALGORITHM
public int rangeBitwiseAnd(int m,int n)
{
while(n>m)
{
n&=(n-1);
}
return m&n;
}
}
// BY FINDING THE COMMON BIT PATTERNS
// public int rangeBitwiseAnd(int m,int n)
// {
// int factor = 1;
// while(m!=n)
// {
// m>>=1;
// n>>=1;
// factor <<=1;
// System.out.println(m+" "+n+" "+factor);
// }
// return m*factor;
// }
// }
// MY METHOD
// public int rangeBitwiseAnd(int m, int n) {
// int sum = m,max = 0;
// if(m==n)
// return m;
// for(int i=m+1;i<=n;i++)
// {
// sum = sum & i;
// max = sum;
// if(i==2147483647)
// break;
// if(sum==0)
// break;
// }
// return max;
// }
// }