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展開二進制位表示暗赶,可以觀察到,結(jié)果取決于m和n左邊有多少相同的bits傅物。
因此設(shè)法找到左邊相同的位,然后再進行位移琉预。
public int rangeBitwiseAnd1(int m, int n) {
int ratio = 1;
while (m != n) {
m >>= 1;
n >>= 1;
ratio <<= 1;
}
return (m * ratio);
}