首页 文章

我的python代码有什么问题(添加二进制代码)? [重复]

提问于
浏览
1

这个问题在这里已有答案:

这是leetcode的一个非常简单的问题:

给定两个二进制字符串,返回它们的总和(也是二进制字符串) . 例如,a =“11”b =“1”返回“100” .

这是我的代码,我认为这没关系

def addBinary(self, a, b):
    if len(a) < len(b):
        a, b = b, a

    rev, temp, sum = list(a[::-1]), 0, ""

    for i, j in enumerate(b[::-1]):
        temp = temp + int(rev[i]) + int(j)
        if temp == 0 or 1:
            rev[i] = str(temp)
            temp = 0
            x2 = temp
        elif temp == 2:
            rev[i] = "0"
            temp = 1

    if temp == 1:
        rev = rev + ["1"]

    for digit in rev[::-1]:
        sum += digit

    return sum

但是当我跑步时,测试无法通过

输入:“1”,“1”输出:“2”预期:“10”

我只是不知道为什么并设置一个断点,发现虽然“temp = temp int(rev [i])int(j)”,temp等于2,但它没有进入elif部分条件因此返回“2”作为最终结果 .

谁能告诉我为什么?我真的很感激 .

2 回答

  • 0

    你有一个错字

    if temp == 0 or 1:
    

    应该是:

    if temp == 0 or temp == 1:
    
  • 2

    一种简单而更加pythonic的做法是:

    def add_binary(a, b):
        return bin(int(a) + int(b))[2:]
    
    print add_binary("1", "1")
    >>> 10
    

相关问题