https://leetcode.com/problems/bitwise-and-of-numbers-range/
Difficulty: Medium
给出区间[m, n],其中0 <= m <= n <= 2147483647,返回这个区间的所有整数相与的结果
只要m和n不同,那么,它们的最后一位肯定是不同的,因为1是最基本的增量单位。由于输入已经是m不大于n,因此,只需要考虑m与n是否相等即可。下面分别给出递归和迭代的算法。
class Solution {
public:
// Runtime: 68 ms
int rangeBitwiseAnd(int m, int n) {
return n > m ? rangeBitwiseAnd(m >> 1, n >> 1) << 1 : m;
}
// Runtime: 68 ms
int rangeBitwiseAnd2(int m, int n) {
int b = 0;
while (m != n) {
if (m == 0) { // Runtime: 64 ms,m为0时结束循环,返回结果,小优化
return 0;
}
++b;
m >>= 1;
n >>= 1;
}
return m << b;
while (n > m) {
n &= (n - 1);
}
return n;
}
};
看一些例子
5 – 101 and 7 – 111 –> 100
5 – 101 and 8 – 1000 –> 0
26 – 11010 and 31 – 11111 –> 11000
26 – 11010 and 32 – 100000 –> 0
当n>m时,每次消去n最末尾的1,直到n<=m,这时的n即为所求的结果
// Runtime: 64 ms
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
while (n > m) {
n &= (n - 1);
}
return n;
}
};