这是一个非常简单的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”作为最终结果。你知道吗
有人能告诉我为什么吗?我真的很感激。你知道吗
你打错了
应改为:
一种更简单、更像Python的方法是:
相关问题 更多 >
编程相关推荐