LeetCode - Bitwise AND of Numbers Range
2015-04-19 23:07
399 查看
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++代码如下:
JAVA代码完全一样,只是bool数组的定义略有不同。
其实bool数组完全可以省略掉,也可以省略掉一些不必要的分支:
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; } };
相关文章推荐
- Leetcode 201 Bitwise AND of Numbers Range 区间内整数按位与
- 【leetcode】Bitwise AND of Numbers Range
- LeetCode(201) Bitwise AND of Numbers Range
- LeetCode Bitwise AND of Numbers Range
- [leetcode][201]. Bitwise AND of Numbers Range
- LeetCode 201 Bitwise AND of Numbers Range (位运算)
- [Leetcode]Bitwise AND of Numbers Range
- Leetcode -- Bitwise AND of Numbers Range
- leetcode_Bitwise AND of Numbers Range
- 【leetcode】Bitwise AND of Numbers Range(middle)
- leetcode -- Bitwise AND of Numbers Range 无聊数学题
- leetcode Bitwise AND of Numbers Range
- leetcode 201: Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range -- leetcode
- LeetCode201——Bitwise AND of Numbers Range
- LeetCode--Bitwise AND of Numbers Range
- 【LeetCode】006 Bitwise AND of Numbers Range 区间内整数按位与
- leetcode Bitwise AND of Numbers Range
- [Leetcode 201, medium] Bitwise AND of Numbers Range
- Leetcode201(Bitwise AND of Numbers Range)