为什么我用 Python 编写的反转位代码会出现此错误?
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 online Judge中,我会得到这个错误:
TypeError: sequence item 0: expected string, int found
此错误由输入 0 引发。
我不知道为什么会引发此错误。我的代码似乎运行良好!
result = [0] * len_str
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
另见 Reverse a string in Python
我在 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 online Judge中,我会得到这个错误:
TypeError: sequence item 0: expected string, int found
此错误由输入 0 引发。
我不知道为什么会引发此错误。我的代码似乎运行良好!
result = [0] * len_str
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
另见 Reverse a string in Python