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.
思路:计算两数之间范围位相与,例如 5的二进制为:0101;
6的二进制为:0110;
7的二进制为:0111;
三个数与运算后为:0100,返回4
目的是找到数前几位相等的部分,两个数每次向右平移1位,平移后当两数相等,向左平移i次,就得到公共部分的数了。
代码如下:
public class BitwiseANDofNumbersRange {
public int rangeBitwiseAnd(int m, int n) {
int i = 0;
while (m != n) {
m >>= 1;
n >>= 1;
++i;
}
return (m << i);
}
}