My Python Solution with 205ms


  • 0
    M

    Use the function of 'reverseBits()' and bits manipulation.

    class Solution:
    
        # 190.
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            n = (n >> 16) | (n << 16)
            n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8)
            n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4)
            n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2)
            n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)
    
            return n
    
        # 201
        # @param m, an integer
        # @param n, an integer
        # return an integer
        def rangeBitwiseAnd(self, m, n):
            if m == n: return m
    
            mm = self.reverseBits(m)
            nn = self.reverseBits(n)
            kk = (mm ^ nn) & (-(mm ^ nn))
            k  = ~((self.reverseBits(kk) << 1) - 1)
    
            return m & n & k

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.