Python solution with detailed explanation

  • 0


    Reverse Bits


    • Keep finding the LSB bit by masking and shifting, Then OR with into the right position in result.
    • Bitwise masking and shifting.
    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            ret, NUM_BITS = 0, 32
            for i in range(NUM_BITS):
                ret = ret | (n&0x1)<<(NUM_BITS-1-i)
                n = n >> 1
            return ret

    Follow up - If this function is called many times, how would you optimize it?

Log in to reply

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