leetcode笔记:Bitwise AND of Numbers Range
2016-03-04 18:19
302 查看
一. 题目描述
Given a range
For example, given the range
二. 题目分析
给定一个范围
单看题目描述,可以知道该题涉及到位运算,因此需动笔分析:
对于题目给定的范围[5, 7],可写为:
再来两个例子:
范围[6, 8]:
范围[8, 10]:
现在可以总结出规律了,对于范围
因此,只有当
三. 示例代码
四. 小结
该题是数学问题,用位运算即可快速解决,主要是要找出规律。
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.
二. 题目分析
给定一个范围
[m, n],其中
0 <= m <= n <= 2147483647,返回范围内所有整数的按位与,包括边界
m和
n。比如给定范围为
[5, 7], 应返回
4。
单看题目描述,可以知道该题涉及到位运算,因此需动笔分析:
对于题目给定的范围[5, 7],可写为:
[code]5: 101 6: 110 -> 100 -> 4 7: 111
再来两个例子:
范围[6, 8]:
[code]6: 0110 7: 0111 -> 0000 -> 0 8: 1000
范围[8, 10]:
[code]8: 1000 9: 1001 -> 1000 -> 4 10: 1010
现在可以总结出规律了,对于范围
[m, n],若
n的最高有效位比
m的最高有效位要高,则必然会出现像例子出现的情况,必然在范围内存在两个数,这两个数分别是对方的反码:
[code]6: 0110 7: 0111 -> 0000 -> 0 8: 1000
因此,只有当
m和
n的最高有效位一致时,即m与n同时右移n位,且
m == n,m == 1时按位与结果不为0,且该结果为
m与
n的公共左边首部,以下给出简单的代码:
三. 示例代码
[code]class Solution { public: int rangeBitwiseAnd(int m, int n) { int bits = 0; while (m != n) { m >>= 1; n >>= 1; ++bits; } return m << bits; } };
四. 小结
该题是数学问题,用位运算即可快速解决,主要是要找出规律。
相关文章推荐
- static const vs. extern const
- ubuntu中的sources.list文件
- Win 8.1/10 如何设置以Administrator身份启动cmd
- Android Studio 上传SVN标准全过程
- HTTPS科普扫盲帖
- HDU 1213 - How Many Tables
- 属性动画
- jquery的ajax同步和异步
- 框架汇总
- POJ 1611 - The Suspects
- 数字游戏
- C++中类所占内存空间的分析(转载)
- ASP.NET分页控件
- 学习进度01
- PM 与 LM 如何分钱问题
- 关于随机数的产生
- An instance of “(null)” is already running. Choose “Stop” to terminate and launch a new instance.
- Linux 后台进程与守护进程
- Android工程的编译过程
- Leet Code OJ 268. Missing Number [Difficulty: Easy]