Python AC with 63ms, 3lines


  • 26
    J
    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            oribin='{0:032b}'.format(n)
            reversebin=oribin[::-1]
            return int(reversebin,2)

  • 0
    X

    Very pythonic


  • 0
    J

    What the function of '032'? Is it same with 0>32b?


  • 3
    D

    similar solution:

    def reverseBits(self, n):
        return int(bin(n)[2:].zfill(32)[::-1], 2)

  • 0
    S
    This post is deleted!

  • 2
    S

    return False if you are doing this on interview else True

    real bit manipulation:

    def reverseBits(self, n):
            res = 0
            for _ in xrange(32):
                res = (res<<1) + (n&1)
                n>>=1
            return res
    

  • 0
    G

    @Seasean

    could you please tell me why my code doesn't work?

        def reverseBits(self, n):
            if n == 0: return 0
            result = 0
            for i in range(32):
                result << 1
                if n & 1 == 1:
                    result += 1
                n >> 1
            return result
    

    result += 1 did int number +1, not binary add.
    why yours work?
    thank you in advance!


Log in to reply
 

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