Skip to main content

67. Add Binary

https://leetcode.com/problems/add-binary

Python

Convert to number and join back

class Solution:
def addBinary(self, a: str, b: str) -> str:
return '{0:b}'.format(int(a, 2) + int(b, 2))

Bit Manipulation

class Solution:
def addBinary(self, a: str, b: str) -> str:
result = []

items_a = list(a)
items_b = list(b)

carry = 0
while items_a or items_b:
bit = carry
if items_a:
bit += 1 if items_a.pop() == '1' else 0
if items_b:
bit += 1 if items_b.pop() == '1' else 0

result.append('1' if bit % 2 == 1 else '0')
carry = bit >> 1

if carry:
result.append('1')

return ''.join(result[::-1])