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.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
方法参考Discuss:
1、考虑上下限的二进制最右位,当且仅当上下限都是1最右位才为1,因此最右一位可以确定;
2、同样的方法,现在我们忽略最右位,以1中同样的方法检查右二位;
3、一直进行,直到上下限的从当前观测位开始向左相等,这个时候再进行下去左边的位置也是可以确定的,是和上下限的值一样的;
代码:
int rangeBitwiseAnd(int m, int n) {
int base = 0;
while (m != n) {
m >>= 1;
n >>= 1;
base++;
}
return m << base;
}