您的位置:首页 > 其它

201. Bitwise AND of Numbers Range

2016-07-26 20:28 375 查看
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.

[5, 7]里共有三个数字,分别写出它们的二进制为:

101  110  111

相与后的结果为100,仔细观察我们可以得出,最后的数是该数字范围内所有的数的左边共同的部分,如果上面那个例子不太明显,我们再来看一个范围[26, 30],它们的二进制如下:

11010  11011  11100  11101  11110

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