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!
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
# 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.