201. Bitwise AND of Numbers Range
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.
显然 m<=n, 当m < n时,最低位的And一定为0(从m到n的二进制数最低位一定存在0),所以最低位为0;我们来看看某一位不为0的情况,就是要找到某一位没有发生二进制上的位变化的位
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
return (n >m)?(rangeBitwiseAnd(m >>1, n>>1) << 1):m;
}
};
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int step = 0;
while(m != n){
m >>= 1;
n >>= 1;
step++;
}
return m<<step;
}
};