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

2024-04-27 05:08:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Given two binary strings, return their sum (also a binary string).

For example, a = "11" b = "1" Return "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

但是,当我运行时,测试无法通过

Input: "1", "1"

Output: "2"

Expected: "10"

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

有人能告诉我为什么吗?我真的很感激。你知道吗


Tags: inforlenreturnifrevtempgiven
2条回答

你打错了

if temp == 0 or 1:

应改为:

if temp == 0 or temp == 1:

一种更简单、更像Python的方法是:

def add_binary(a, b):
    return bin(int(a) + int(b))[2:]

print add_binary("1", "1")
>>> 10

相关问题 更多 >