One line solution in Python :)


  • 11
    J

    I love Python! It has such a lot of cool features with string manipulation, such as slicing.

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

    Runtime is 52ms. Slower than most solutions posted here though. I'm just trying to get my hands dirty on Python :)


  • 0
    X

    your solution is very smart,i like it


  • 1
    W

    My Solution is similar to yours

    class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        str_bin = bin(n)[2:]
        if len(str_bin) < 32:
            str_bin = (32-len(str_bin))*'0' + str_bin
        return int('0b'+str_bin[::-1], 2)

  • 0
    W

    Cool
    I forgot the zfill funtion,so it became more than one line. 2333


  • 0
    A

    ehhh……complete the same solution


  • 0
    J

    hmm.... mine which I solved 2 years ago as well has runtime 59ms
    take a look:

    def reverseBits(self, n):
        return int(('%0*d' % (32, int(bin(n)[2:])))[::-1], 2)

  • 0
    F

    @woodrat sorry, may I know why the slice of bin starts from 2?
    str_bin = bin(n)[2:]


  • 0
    O

    Nice! Here's my similar attempt:

    def reverseBits(self, n):
        return int("{:032b}".format(n)[::-1], 2)
    

Log in to reply
 

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