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;
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章