It's a very simple problem from leetcode:
Given two binary strings, return their sum (also a binary string).
For example, a = "11" b = "1" Return "100".
Here is my code, I think it's just okay
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
However as I run, a test can't pass
Input: "1", "1"
Output: "2"
Expected: "10"
I simply don't know why and set a break point, finding that though "temp = temp + int(rev[i]) + int(j)", temp was equalled to 2, it didn't go to the elif part of the condition and thus returns "2" as the final result.
Could anyone tell me why? I really appreciate that.