【发布时间】:2016-07-16 07:51:49
【问题描述】:
对于我们的家庭作业,我们被要求输入一个整数并返回它的二进制补码。
目前,我能够将整数转换为二进制字符串。从那里,我知道我需要反转 0 和 1 并将 1 添加到新字符串中,但我不知道该怎么做。
有人可以帮我解决这个问题吗?
def numToBinary(n):
'''Returns the string with the binary representation of non-negative integer n.'''
result = ''
for x in range(8):
r = n % 2
n = n // 2
result += str(r)
result = result[::-1]
return result
def NumToTc(n):
'''Returns the string with the binary representation of non-negative integer n.'''
binary = numToBinary(n)
# stops working here
invert = binary
i = 0
for digit in range(len(binary)):
if digit == '0':
invert[i] = '1'
else:
invert[i] = '0'
i += 1
return invert
注意:这是入门级课程,所以我们主要坚持使用loops 和recursion。除了基础之外,我们不能真正使用任何花哨的字符串格式、内置函数等。
【问题讨论】:
-
既然是作业——我觉得只能给个提示。在 PHP 手册中查找您的二进制操作。使用在线手册。其中一位会告诉你如何做到这一点。
-
冒着放弃分配的风险,请注意 Python 定义了一些非常有用的 bitwise operators...
-
让我猜猜,你有
TypeError: 'str' object does not support item assignment,不是吗?请附上您在发布问题时收到的错误消息,这样可以大大更轻松地帮助您解决实际问题。 -
@Liongold 谢谢你的链接。我能够解决它。
-
@MarkManning 感谢您的洞察力。我能弄明白。
标签: python binary twos-complement