题目:
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.
题意:
给定一个区间,找出该区间所有元素“与”之后的结果。
思路:
这道题是一道bit 操作的题目。首先考虑如果区间是[k,k]那么返回值就是k。如果区间是[m,n],即此时n > m,那么从m变化到n这些数字,bit的最低位最后的“与”的结果一定是0,因为从m变化到m+1,如果m的最低位是0,那么此时变化到1,与之后这一位肯定还是0,如果m最低位是1,那么m+1最后一位肯定是0.所以与的最终结果最低位肯定还是0.
所以可以递归的求解结果。如果m == n,那么结果就是n,如果n > m,那么它们的最低位肯定是0,此时只需去计算n/2与m/2的结果,然后将结果左移一位。
下面是递归与非递归的两种实现方法,递归在注释的部分。
代码如下:
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
//return (n > m)?(rangeBitwiseAnd(m >> 1, n >> 1) << 1):m;
int count = 0;
while(n != m)
{
m >>= 1;
n >>= 1;
count++;
}
return (m<<count);
}
};