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);
}
网友评论