标签:leetcode
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.
① n&(n-1),可以去除n的最低位的1。
② 从n一直与到m,可以去掉的1就是n和m的右端不相等的部分的1。
例如对于如下m和n:
110100111101 –>m
110111111111 –>n
可以去掉的就是n的红色部分的1。
//Runtime:100ms
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
char bit = 0;
while (m != n)
{
m >>= 1;
n >>= 1;
bit++;
}
return m << bit;
}
};
[LeetCode] Bitwise AND of Numbers Range
标签:leetcode
原文地址:http://blog.csdn.net/foreverling/article/details/45370263