LeetCode - Bitwise AND of Numbers Range
来源:互联网 发布:青岛海尔软件地址 编辑:程序博客网 时间:2024/06/11 11:29
https://leetcode.com/problems/bitwise-and-of-numbers-range/
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挨个AND,结果超时了,后来发现既然是AND,那么只需要看m和n的每个bit就行,如果m,n的某位bit不同,那么m, n的范围内肯定在这个bit后面的bit所有后面的bit里面有交替的0,1变化,所以AND后这个bit及其后面的所有bits都应该为0,由此看来,就直接看m, n每位的值是否相同,然后找到最高的不同位,则这一位及后面所有都为0,这一位之前的保存m本身的值。例如:
000
001
010
011
100
可以看到,在第3位不同的情况下,不管后面两位的范围如何,他们AND出来的结果肯定都是0。因此C++代码如下:
class Solution {public: int rangeBitwiseAnd(int m, int n) { if(m==n) return m; bool same[32]; for(int i=0; i<32; i++){ if(((m>>i)&1) == ((n>>i)&1)) same[i] = true; else same[i] = false; } int i=31; while(i>=0 && same[i]) i--; if(i==-1) return m; int rst = (~((1<<(i+1))-1)) & m; return rst; }};
JAVA代码完全一样,只是bool数组的定义略有不同。
其实bool数组完全可以省略掉,也可以省略掉一些不必要的分支:
class Solution {public: int rangeBitwiseAnd(int m, int n) { int i=31; while(i>=0 && ((m>>i)&1) == ((n>>i)&1)) i--; return (~((1<<(i+1))-1)) & m; }};
0 0
- mahout-0.9源码编译过程
- TCP的三次握手(建立连接)和四次挥手(关闭连接)
- Atom类源码分析
- iOS app中使用webview的时机
- [leetcode](Remove Duplicates from Sorted List II C语言实现)
- LeetCode - Bitwise AND of Numbers Range
- 手把手教你如何恢复SD卡误删文件
- M牛C原创博客——oc中设计模式之——单例模式
- elasticsearch__5__java操作之fact
- 关于android中PendingIntent.getBroadcase的注册广播
- 【C++、SQL学习笔记3】杂记
- 中国开源社区
- SVN的使用——基本知识,Server搭建与Client日常使用维护
- 如何优化MySQL insert性能