1. 程式人生 > >LeetCode[Bitwise]----Bitwise AND of Numbers Range

LeetCode[Bitwise]----Bitwise AND of Numbers Range

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,返回m到n閉區間內所有元素位運算&後的結果。

我們知道a和b進行And操作時,在a和b同時為1的時候結果才為1.

假設m的位表示為xyzabc,n的位表示為xyzdef,此時m & m+1 & ... & n的結果為xyz000。這句話的意思是說,m到n所有數字與的結果等於m到n之間所有相同位的結果(比如m到n所有數字位相同的為x,y和z),引申一下可以理解為m到n所有數字與的結果為m和n這兩個數字之間所有相同位的結果。依據這個結論我們可以快速的計算出任意兩個數字之間所有數字And的結果。


程式碼為:

class Solution(object):
    def rangeBitwiseAnd(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        i = 0
        while m != n:
            m >>= 1
            n >>= 1
            i += 1
        return m<<i