Bitwise AND of Numbers Range JAVA
2015-04-29 14:33
120 查看
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的所有值做AND操作后的结果。
简单暴力直接与应该也能得到正确的结果,但是肯定超时。
而且最蛋疼的地方是,leetcode有一个测试例,是2147483647, 2147483647。在这个测试例下,直接判断if(m==n) return m;还是回超时。
想了一下,然后思路都不是很好,但是,讨论区的一个方法着实让我眼前一亮,源地址如下:
https://leetcode.com/discuss/32017/my-simple-java-solution-3-lines
程序如下:
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的所有值做AND操作后的结果。
简单暴力直接与应该也能得到正确的结果,但是肯定超时。
而且最蛋疼的地方是,leetcode有一个测试例,是2147483647, 2147483647。在这个测试例下,直接判断if(m==n) return m;还是回超时。
想了一下,然后思路都不是很好,但是,讨论区的一个方法着实让我眼前一亮,源地址如下:
https://leetcode.com/discuss/32017/my-simple-java-solution-3-lines
程序如下:
public int rangeBitwiseAnd(int m, int n) { int r=Integer.MAX_VALUE; while((m&r)!=(n&r)) r=r<<1; return n&r; }
相关文章推荐
- Java for LeetCode 201 Bitwise AND of Numbers Range
- Java 位运算2-LeetCode 201 Bitwise AND of Numbers Range
- 【LeetCode-面试算法经典-Java实现】【201-Bitwise AND of Numbers Range(范围数位与结果)】
- Bitwise AND of Numbers Range
- leetcode--Bitwise AND of Numbers Range
- [LeetCode] Bitwise AND of Numbers Range 数字范围位相与
- Leetcode: Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range
- LeetCode(201) Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range问题及解法
- 【leetcode】 Bitwise AND of Numbers Range
- *LeetCode-Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range
- LeetCode - Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range -- leetcode
- LeetCode解题报告—— Number of Islands & Bitwise AND of Numbers Range
- LeetCode -- Bitwise AND of Numbers Range
- leetcode 201: Bitwise AND of Numbers Range
- 《leetCode》:Bitwise AND of Numbers Range
- LeetCode201--Bitwise AND of Numbers Range