[英]Why my reversing bits code written in Python gets this error?
我在Leetcode中遇到了這個問題: https ://leetcode.com/problems/reverse-bits/
所以輸入將是一個十進制整數,我必須將其轉換為32位二進制。
然后我將其反轉並將其返回到十進制。
例如:
輸入:
8 (whose binary == 1000)
輸出:
1 (whose binary == 0001)
這是我的代碼:
# 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)
如果我在Leetcode在線法官中運行此代碼,則會收到此錯誤:
TypeError: sequence item 0: expected string, int found
輸入0引發此錯誤。
我不知道為什么會引發這個錯誤。 我的代碼似乎運行良好!
result = [0] * len_str
len_str
是一個int值,但是len_str
是一個字符串。 那條線應該發生什么? 也許:
result = ['' for x in xrange(len_str)]
初始化一個大小為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)
產量
<class 'str'> 0001
<class 'int'> 8
另請參閱在Python中反轉字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.