[LeetCode] 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.

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

101　　110　　111

11010　　11011　　11100　　11101　　11110

class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int d = INT_MAX;
while ((m & d) != (n & d)) {
d <<= 1;
}
return m & d;
}
};

class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int i = 0;
while (m != n) {
m >>= 1;
n >>= 1;
++i;
}
return (m << i);
}
};

class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
return (n > m) ? (rangeBitwiseAnd(m / 2, n / 2) << 1) : m;
}
};

class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
while (m < n) n &= (n - 1);
return n;
}
};

https://discuss.leetcode.com/topic/13508/one-line-c-solution

https://discuss.leetcode.com/topic/12133/bit-operation-solution-java

https://discuss.leetcode.com/topic/20176/2-line-solution-with-detailed-explanation

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2015-04-16 11:53  Grandyang  阅读(20604)  评论(8编辑  收藏  举报