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.
思路:
变成二进制位的话,无论中间有多少个数,只要range的头尾转换成二进制,然后从左向右找相等的就可以了。。写个例子吧,从11110001到11111010取and,得到的结果应该是11110000.
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int res=0;
while(m&&n)
{
if(m==n)
{
return m<<res;
}
m=m>>1;
n=n>>1;
res++;
}
return 0;
}
};