卖萌的弱渣

I am stupid, I am hungry.

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.

Solution

最后的与肯定是从某一位开始都相同,那么我们只需要看最大和最小的两个数,从哪一位开始是相同的,也就是看最大和最小的两个值的高几位相同。 当然我们也可以使用从高位往地位判断,有多少位是相同的。

(Bitwise-and-of-Numbers-Range.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
    def rangeBitwiseAnd(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        p = 0
        while m!=n:
            m = m>>1
            n = n>>1
            p+=1
        return m<<p