Share a simple four line python solution using bit operation

  • 3

    It seems that no one has post this solution which is pretty simple.

    If we go through all the numbers from m to n, only those digits which are constantly 1 can remain to be 1 at last. So we simply operate m xor n to calculate the number of zeros at the end of result.

    The final result should be n>>zeors concatenates to zeros. Here is the code.

    class Solution:
    # @param {integer} m
    # @param {integer} n
    # @return {integer}
    def rangeBitwiseAnd(self, m, n):
        if m == n:
            return m
        zeros = len(bin(m^n)) - 2
        return (n >> zeros) * (2**zeros)

  • 0

    The function of 'bin' count '0b' into length, which seems odd

  • 0

    Yes it's odd. I tried 'math.log(m^n, 2)' at first but it seems to be much slower than the function of 'bin'.

  • 0

    I prefer:
    return (n >> zeroes) << zeroes

  • 0

    yeah, it's the better one.

Log in to reply

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