One line Python solution with brief explanation


  • 1
    W

    My basic idea is:

    1. Convert the given integer to an 32-bit binary string;
    2. Reverse the string;
    3. Convert it back to integer and return

    For step 1: we can use '{0:032b}.format() to do it. The first '0' means that we will format the 0th(the first) argument; and the second '0' represents the padding symbol; '32' means total length of the output and 'b' represents binary.
    After this, we can use slicing and built-in functions to finish.

    By the way, I personally don't like the one-line code, because I think readability is very important while some people are kind of crazy about very short code; Another thing is that, although Python provides a lot powerful built-in functions, but don't rely too much on it.
    Have fun.

    class Solution:
      def reverseBits(self, n):
        return int('{0: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.