【问题标题】:My binary subtraction program seems to not work for one specific value我的二进制减法程序似乎不适用于一个特定的值
【发布时间】:2020-10-24 11:05:13
【问题描述】:

所以我正在制作这个减法程序,真的不知道为什么它不适用于这两个值。但对于其他每个它都有效吗?

def binmin(x, y):
    lenx = len(x)
    leny = len(y)
    x1 = list(x)
    y1 = list(y)
    difference= 0
    one = 0
    result = ""
    for i in range(len(x)):
        difference = str((int(x1[lenx - 1 - i])) - int(y1[leny - 1 - i]))
        if difference == "-1":
            difference = 2 - int(y1[leny - 1 - i])
            one = 1
        
        elif difference == "-2":
            one = 1
            difference = 0

        else:
            one = 0

        y1[leny - i - 2] = int(y1[leny - i - 2]) + one

        result = str(difference) + str(result)

    return result

print(binmin("11110000","00010001"))

【问题讨论】:

    标签: python binary subtraction


    【解决方案1】:

    变化:

    if difference == "-1":
        difference = 2 - int(y1[leny - 1 - i])
        one = 1
    

    到:

    if difference == "-1":
        difference = 1
        one = 1
    

    difference 最初是"-1" 时,您需要借用,因此您实际上是将2 添加到差异中。由于差异最初是 -1,因此您需要 2-1 = 1 来获得新差异。

    原始调整仅在 int(y1[leny - 1 - i])1 时才有效,如果先前已通过较早的借用进行调整,则可能无效,在这种情况下,它可能为 2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 2012-03-13
      • 1970-01-01
      • 2020-04-12
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多