title: Interview: Adding two binary numbers given as strings
body: <p>While looking through some interview questions at <a href="http://www.glassdoor.com/Interview/Facebook-Interview-Questions-E40772.htm" rel="nofollow">http://www.glassdoor.com/Interview/Facebook-Interview-Questions-E40772.htm</a> I came across the following question:</p>
  
  <blockquote>
    <p>Given two string representations of binary numbers (e.g. "1001", "10") write a function that adds them and returns the result as a string as well (e.g. "1011").</p>
  </blockquote>
  
  <p>Here's some Python code that I started to write for the problem (it is incomplete right now), but I am not very sure if this is the best (or even correct) approach. I also thought about implementing the same in C++ first, but gave up considering the added complexities in string manipulations.</p>
  
  <pre><code>def add_binary(a,b):
      temp = ""
      carry = false
      //i from len(a) to 1 and j from len(b) to 1
      bit_sum = add_bit ((a[i],b[j])
      if (bit_sum == "10"):
              temp.append("0")
              carry = true
      elif carry:
              temp.append(add_bit("1",bit_sum))
      else:
              temp.append(bit_sum)
  
      return temp.reverse()
  
  
  def add_bit(b1, b2):
      if b1 == '0':
              return b2
      elif b2 == '0':
              return b1
      elif (b1 = '1' and b2 =='1'):
              return "10"
      else return None
  
  a = "1001"
  b = "10"
  add_binary(a,b)
  </code></pre>