Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
Solution1
https://yq.aliyun.com/articles/3512
// https://yq.aliyun.com/articles/3512
public int rangeBitwiseAnd(int m, int n) {
int count = 0;
while (m != n) {
m = m >>> 1; // shift numbers right
n = n >>> 1; // shift numbers right
count = count + 1; // keep track of Shifts
}
return n << count; // do left shifts with 0 padding and return answer.
}
Solutioin 2
public int rangeBitwiseAnd2(int m, int n) {
int r = Integer.MAX_VALUE;
while ((m & r) != (n & r))
r = r << 1;
return n & r;
}