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;
}
};
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;
}
};
相关文章推荐
- visual studio 2015安装.net core 问题
- HDU 5761 Rower Bo
- 使用 CXF 做 webservice 简单例子
- Codeforces 439D Devu and his Brother
- JS数组实现队列和堆栈
- linux基础1
- 【CodeForces】371C - Hamburgers(二分)
- 单例模式深入学习
- Android Studio 导入第三方jar包
- c#之用StreamWriter追加写文件
- 重复元素的删除问题
- Failed to instantiate * using constructor public * with arguments **
- 【HDU 1950】Bridging signals(LIS算法求最长上升子序列)
- android ListView 记录当前位置 恢复
- 操蛋的Camera V2
- linux文件系统及文件属性
- MVC中Controller中的跳转
- 再谈‘进程’
- 网编基础(2)
- bootstrap3上传特效