1

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.

Community
  • 1
  • 1
tonyabracadabra
  • 319
  • 2
  • 10

2 Answers2

2

You have a typo

if temp == 0 or 1:

should instead be:

if temp == 0 or temp == 1:
Aaron D
  • 5,817
  • 1
  • 36
  • 51
0

A simple and more pythonic way of doing the same is:

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

print add_binary("1", "1")
>>> 10
ZdaR
  • 22,343
  • 7
  • 66
  • 87