Python one-liner using zfill

  • 0
    def reverseBits(self, n):
        return  int(format(n, 'b').zfill(32)[::-1], 2)

    To be honest, it's not the most readable solution. But it's fast.

    What happens is it first formats the int as a binary string representation padded to 32 places (using zfill), then reverses the string and casts it to a base-10 integer. As we know it's unsigned we don't need to worry about edge cases using the signing bit.

Log in to reply

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