您的位置:首页 > 其它

[leetcode][bit] Bitwise AND of Numbers Range

2015-05-23 16:03 363 查看
题目:

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.
方法一:
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
//设从最高位开始第一个m和n不同的位为i,则从i开始其后的所有位都为0
unsigned mask = 1 << 31;
int res = 0;
while (mask){
if ((mask & m) != (mask & n)) break;
res = res | mask & m;
mask = mask >> 1;
}
return res;
}
};


方法二:

class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int offset = 0;
while(m != n){
m >>= 1;
n >>= 1;
offset++;
}
int res = m << offset;
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: