2 lines recursive Python


  • 0

    First let's have some observation. For example, m == 5 and bin(m) == '0b101'. If n == 8, then bin(n) == '0b1000'. We can easily see the answer is 0 when len(bin(m)) < len(bin(n)).

    Okay, what if len(bin(m)) == len(bin(n))? We just add the first bit into our accumulative answer and recursively processing for both m and n without first bit in their binary representation.

    class Solution(object):
        def rangeBitwiseAnd(self, m, n):
            """
            :type m: int
            :type n: int
            :rtype: int
            """
            mask = 1 << len(bin(n)) - 3
            return 0 if not m or len(bin(m)) < len(bin(n)) else \
                   mask + self.rangeBitwiseAnd(m & (mask-1), n & (mask-1))
    

Log in to reply
 

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