Value error in string formatting in Python


  • 0
    M
    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            n = int(n)
            binaryFormat = '{0:0>32b}'.format(n)
            reverseContainer = []
            for i in range(1, 32):
                reverseContainer.append(binaryFormat[-i])
            return "".join(reverseContainer)
    

    Here attaches my source code.
    I am pretty sure that this code works in Python 2.7.4 environment. But, when I submitted it here, it reported an error as below:
    ValueError: Unknown format code 'b' for object of type 'str'


  • 1
    C

    you should return integer instead.What's more, your code only executes 31 times.In fact, it should execute 32 times.

    Here is the correct code:

    def reverseBits(self, n):
        n = int(n)
        binaryFormat = '{:0>32b}'.format(n)
        reverseContainer = []
        for i in range(1, 33):
            reverseContainer.append(binaryFormat[-i])
        return int("".join(reverseContainer), base=2)
    

    The reversion can be simple.Here is my code

    def reverseBits(self, n):
        n_bin = '{:0>32b}'.format(n)
        return int( n_bin[::-1], base=2)

  • 0
    M

    Thanks for your solution. It helps a lot.


Log in to reply
 

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