LeetCode:Bitwise AND of Numbers Range
2016-06-11 20:16
267 查看
Bitwise AND of Numbers Range
Total Accepted: 35825 TotalSubmissions: 115763 Difficulty: Medium
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.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
Bit Manipulation
思路:
[m,n]中的所有数做“与”运算时,结果中第i位为1的条件是[m,n]中所有第i位都为1,否则为0。
因此,只需要判断m与n的最高位是否同时为1,不同时为1的话,结果为0;
同时为1时,假设这一位是第i位,这时结果为1<<i,即2^i。
java code:
public class Solution {
public int rangeBitwiseAnd(int m, int n) {
int moveCount = 0;
while(m!=n) {
m >>= 1;
n >>= 1;
moveCount++;
}
return m <<= moveCount;
}
}
相关文章推荐
- jQuery EasyUI-动态改变主题
- iOS 加载图片选择imageNamed 方法还是 imageWithContentsOfFile?
- java.lang.Class.getComponentType()方法
- poj2046
- vs2012 boost配置
- 第二阶段冲刺个人博客07
- POJ 2986 A Triangle and a Circle
- Android Studio导入项目的几种方法
- spring结合quartz实现定时任务
- spring配置工厂bean
- Linux下定时执行任务的方法
- GUID
- LeetCode-75.Sort Colors
- Tensorflow实验环境搭建
- CSS 选择器参考手册
- 用正则表达进行对每个中文进行匹配而分割
- Qt之QTableWidegt类常见用法
- Linux系统修改编码
- C# 图形设计
- 第一篇博客,试水 关于开发板挂载u盘的问题