版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26440803/article/details/80919622
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
解析:
大概意思是找出m,n 二进制表示数的最高位相同的位数
11001
11010
11011
11100
结果为11000
,即截取最高位相同的部分
解法一:循环右移
m,n不断右移一位,知道m==n,并记录下移动的次数,在将m 左移回来
代码
public int rangeBitwiseAnd(int m, int n) {
int count = 0;
while(m != n){
m >>= 1;
n >>= 1;
count++;
}
return m<<=count;
}
解法二:截取最低位
循环截取n的最低位,当出现n < m时,即为所求。
代码
public int rangeBitwiseAnd(int m, int n) {
while (m < n) n &= (n - 1);
return n;
}