将二进制字符串转换为二进制补码

Convert binary string into two's complement

对于我们的家庭作业,我们被要求输入一个整数和 return 它的补码。

目前,我可以将整数转换为二进制字符串。从那里,我知道我需要反转 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

注意:这是入门级课程,所以我们主要坚持使用loopsrecursion.我们不能真正使用任何花哨的字符串格式、内置函数等。

我通过执行以下操作找到了我的解决方案:

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)
    for digit in binary:
        if int(digit) < 0:
            binary = (1 << 8) + n
    return binary