LeetCode201 Bitwise AND of Numbers Range Java 题解

题目:

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:101  7:111  连续几个数相与的规律:一,仅仅要是同样的位置的数字不同样最后那个位置的结果一定是0 。二,假设高位不同样,从不同样的那位到最低位都会为0,比如5和7尽管第0位同样可是因为第一位不同样,所以最后结果第0位 和第一位都为0。  

假设理解了第二个规律就好办了,假设另个数位数不同样肯定最后结果为0。假设位数同样,从最高位開始寻找,将第一次发现不同样的那一位到最低位都置为0;


代码中,通过不断地右移直到两个数字相等。然后再左移同样的位数。这样做的效果事实上就是将位置不同样的都置为0


代码:

public static int rangeBitwiseAnd(int m, int n) {

int count=0;
while(m!=n)
{
m=m>>>1;
n=n>>>1;
count++;
}
return m<<count;


        
    }