LeetCode 201 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.

这个题开始想了想,以为直接loop就行了,但是又一想好歹是个中等难度,有这么简单?管他呢就简单loop。果然==Time Limit Exceeded。那有什么骚操作呢?就参考了别人的解法。有这么一个思路。说结果取决于所有数字的最左公共部分。举例:

4:0100

5:0101

6:0110

7:0111

结果是0100,也就是4.但是不用所有的数字都计算了,只要计算开头结尾就行了。因为他们的最左公共部分是最短的。

因此得到代码:

 

 

1
2
3
4
5
6
7
8
9
public int rangeBitwiseAnd(int m, int n) {
		int i = 0;
		while (m != n) {
			m >>= 1;
			n >>= 1;
			i++;
		}
		return m < < i;
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章