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.
Solution: if m == n return m
if(m != n) we can divide m and n into to part
m1 | m2 n1 | n2 and m1 == n1, m1 is the longest common prefix of m and n.
for the part m2 and n2 it must be zero since there must be at least one 0 at each bit.
Code:
public class Solution {
public int rangeBitwiseAnd(int m, int n) {
int k = 0;
while(m != n){
m >>= 1;
n >>= 1;
k++;
}
return m << k;
}
}