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左邊有多少相同的bits。
因此設法找到左邊相同的位,然后再進行位移。
public int rangeBitwiseAnd1(int m, int n) {
int ratio = 1;
while (m != n) {
m >>= 1;
n >>= 1;
ratio <<= 1;
}
return (m * ratio);
}