您的位置:首页 > 编程语言 > Java开发

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

程序如下:

public int rangeBitwiseAnd(int m, int n) {
int r=Integer.MAX_VALUE;
while((m&r)!=(n&r))  r=r<<1;
return n&r;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: