Reverse Bits

Question

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Tag

  • Bit Manipulation

Thought

For python, just get the list of the binary string and reverse it. Then, convert it back.

Another way is to use format and zfill function.

Code

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        binary_str = list(bin(n))[2:]
        binary_str.reverse()
        length = len(binary_str)
        num_zero = 32 - length
        binary_str = binary_str + ['0'] * num_zero
        num = ''.join(binary_str)
        return int(num, 2)

Use format and zfill function

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        ans = format(n, 'b').zfill(32)[::-1]
        return int(ans, 2)

results matching ""

    No results matching ""