201. 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.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
Approach
- 题目大意是返回m和n范围内的所有数字进行与操作的结果。这道题不是模拟题,如果直接按题意模拟必然会超时,多举几个例子会发现,题目是要求你找它们二进制的公共前缀,这里贴两种代码,一个是比较通俗易懂但效率一般的代码,还有一个需要推敲但效率极高的代码。
Code
One
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
if (m == n)return m;
int len = 0, tm = m, tn = n;
while (tm > 0 && tn > 0) {
tm >>= 1;
tn >>= 1;
++len;
}
if (tn != 0)return 0;
int ans = 0;
for (int i = len - 1; i >= 0; --i) {
int a = ((m >> i) & 1), b = ((n >> i) & 1);
if (a == b) {
ans |= (a << i);
}
else {
break;
}
}
return ans;
}
};
Two
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
if (!m)return 0;
unsigned int s = UINT_MAX;
while ((m&s) != (n&s)) {
s <<= 1;
}
return s&m;
}
};