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.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
这题解题的思路有点巧妙,对m到n是连续的与操作,我们知道,低位肯定为0,但是到哪为止不知道,举个例子:
对于 26 to 30
它们的二进制为:
11010
11011
11100
11101
11110
可见,在m>n的前提下,对于最后一位,不管任何情况,肯定为0,于是问题就转换成了13-15的连续与问题,即m,n都左移一位;如果m仍然大于n,则m,n继续左移一位,直到m==n
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
if(m == 0)
return 0;
int res = 1; //记录是哪一位
while(m != n)
{
m = m >> 1;
n = n >> 1;
res = res << 1;
}
return m * res;
}
};