Leetcode -- Bitwise AND of Numbers Range
2015-09-01 21:16
246 查看
题目:
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.
分析:
将[m, n]里面的数字进行与操作。
思路:
1。 遍历一遍,代码少,结果一定正确,但是会超时。
2。m ^(m+1)^(m+2)^(m+3)……^n, 最后留下来的,就是m和n从高位开始相同的数了。比如:101^110^111, 最后留下来的是100, 110^111^1000, 结果就是0。那么现在的问题就是如何找到相同的高位了。
代码:
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.
分析:
将[m, n]里面的数字进行与操作。
思路:
1。 遍历一遍,代码少,结果一定正确,但是会超时。
2。m ^(m+1)^(m+2)^(m+3)……^n, 最后留下来的,就是m和n从高位开始相同的数了。比如:101^110^111, 最后留下来的是100, 110^111^1000, 结果就是0。那么现在的问题就是如何找到相同的高位了。
代码:
class Solution { public: int rangeBitwiseAnd(int m, int n) { int num = m; int res = n-m; int res1 = ~0; while(res) { res = res >> 1; res1 = res1 << 1; } return num & res1 & n; } };
相关文章推荐
- Varnish Install And Configure
- C/C++位操作实例总结
- Insert Date and Time into Access
- 拖动Html元素集合 Drag and Drop any item
- C++位操作的常见用法小结
- 学习drag and drop js实现代码经典之作
- And,Where使用提示以及用+进行左关联的提示及注意事项
- Android开发adb.exe' and can be executed.错误解决方法
- Table ‘xxx’ is marked as crashed and should be repaired 错误解决方法参考
- drag-and-drop实现图片浏览器预览
- python关键字and和or用法实例
- Python and、or以及and-or语法总结
- Python中AND、OR的一个使用小技巧
- Nginx中IF、AND、OR语句用法实例
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 负载均衡及会话保存(Ofbiz框架)
- Due Care and Due Diligence