0

I get this problem in Leetcode: https://leetcode.com/problems/reverse-bits/

So the input will be a decimal integer and I have to turn it into binary 32 bits.

And then I reverse it and turn it back to decimal.

For example:

Input:

8 (whose binary == 1000)

Output:

1 (whose binary == 0001)

Here is my code:

# n is input number
str1 = str('{0:0{1}b}'.format(n,32))
len_str = len(str1)
index_swap = len_str - 1
result = [0] * len_str

for i, char in enumerate(str1):
    result[index_swap-i] = char

return int(str(''.join(result)),2)

If I run this code in Leetcode online Judge, I will get this error:

TypeError: sequence item 0: expected string, int found

This error is raised by the input 0.

I have no idea why it will raise this error. My code seems to works well!

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
Mars Lee
  • 1,845
  • 5
  • 17
  • 37

2 Answers2

2
result = [0] * len_str

len_str is an int but a string was expected. What should happen in that Line? Maybe:

result = [''  for x in xrange(len_str)]

which initialize an empty string of size len_str

Mailerdaimon
  • 6,003
  • 3
  • 35
  • 46
  • 1
    For all future readers: Look at the Answer from Lutz Horn for a Pythonic solution. My Answer only aims at answering the question without giving code advice (which should be done at Code Review SE ;). – Mailerdaimon Mar 16 '16 at 08:00
1
# There ...
a = 8
b = "{0:b}".format(8)[::-1]
print(type(b), b)

# and back again.
c = int(b[::-1], base=2)
print(type(c), c)

Output

<class 'str'> 0001
<class 'int'> 8

See also Reverse a string in Python