leetcode Bitwise AND of Numbers Range
2015-09-13 18:49
309 查看
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.
这题考的是位操作
需要探索的一个基本式子是 (n & (n - 1))
假设有这样一个数xxxxxxxxxxx10000(这里示意的是最右边一个为1的位,x表示可为1可为0)
那么n - 1 = xxxxxxxxxxx01111
n & (n - 1)呢?
我们发现恰好将最右边那个1消去了.
等等,似乎还有信息可以发掘n = xxxxxxxxxxx10000, n - 1 = xxxxxxxxxxx01111, n & (n - 1) = xxxxxxxxxxx00000
有没有发现 n 和 (n & (n - 1))之间差了可不只1啊, 那这之间的数是个什么形式呢??
n = xxxxxxxxxxx10000
n - 1 = xxxxxxxxxxx01111
xxxxxxxxxxx01110
......
xxxxxxxxxxx0xxxx
......
n & (n - 1) = xxxxxxxxxxx00000
有没发现,所有这些数相与的结果就是n & (n - 1)
所以解法就很简洁了:
For example, given the range [5, 7], you should return 4.
这题考的是位操作
需要探索的一个基本式子是 (n & (n - 1))
假设有这样一个数xxxxxxxxxxx10000(这里示意的是最右边一个为1的位,x表示可为1可为0)
那么n - 1 = xxxxxxxxxxx01111
n & (n - 1)呢?
我们发现恰好将最右边那个1消去了.
等等,似乎还有信息可以发掘n = xxxxxxxxxxx10000, n - 1 = xxxxxxxxxxx01111, n & (n - 1) = xxxxxxxxxxx00000
有没有发现 n 和 (n & (n - 1))之间差了可不只1啊, 那这之间的数是个什么形式呢??
n = xxxxxxxxxxx10000
n - 1 = xxxxxxxxxxx01111
xxxxxxxxxxx01110
......
xxxxxxxxxxx0xxxx
......
n & (n - 1) = xxxxxxxxxxx00000
有没发现,所有这些数相与的结果就是n & (n - 1)
所以解法就很简洁了:
int rangeBitwiseAnd(int m, int n) { while(n > m) n &= n - 1; return n; }
相关文章推荐
- JavaScript权威设计--JavaScript对象(简要学习笔记七)
- HDU 5442 Favorite Donut 后缀数组
- Myql where子句IN的使用方法
- 邮件解码---GMIME的使用其实很简单
- ResponseCode 404
- keystone-all 代码分析
- 包装类和Map接口的使用
- 编写一个业务函数,实现按行读取文件。把内容按照第三种内存模型打包数据传出,把行数通过函数参数传出。
- C#读取Word模板替换相应的字符串(标签)生成新的Word
- Android中Intent概述及使用
- ubuntu preseed 安装文档
- 2016阿里巴巴校招内推offe之JAVA研发工程师
- HDU 5439. Aggregated Counting (2015长春网络赛C题)
- Java记录 -30- 包装类
- browser-sync的使用
- MFC树形控件(CTreeCtrl)用法(下)
- 编写一个业务函数,实现字符串(前后各有三个空格,单词前后也均有空格) " i am student, you are teacher " , 各个单词首字符大写
- AngularJs学习
- 使用Reflector反编译.NET程序的经验
- 机器学习-浅谈特征选择