Problem: Given two binary strings, return their sum (also a binary string).
For example, add_binary_strings('11', '1') should return '100'.
Implementation 1:
def addBinary(a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a = a[::-1]
b = b[::-1]
carry = '0'
result = ''
# Pad the strings to make their size equal
if len(a) < len(b):
for i in range(len(a), len(b)):
a += '0'
elif len(a) > len(b):
for i in range(len(b), len(a)):
b += '0'
n = len(a)
carry = 0
s = ''
for i in range(n):
l, m, c = int(a[i]), int(b[i]), carry
s += str(l^m^c) # sum is XOR of three bits
carry = (l&m) | (m&c) | (c&l) # carry is pairwise AND of three bits
if carry == 1:
s += str(carry)
return s[::-1]
Implementation 2
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a = a[::-1]
b = b[::-1]
m = min(len(a), len(b))
carry = '0'
result = ''
for i in range(m):
r, carry = add_digit(a[i], b[i], carry=carry)
result += r
larger, shorter = a, b
if len(a) < len(b):
larger, shorter = b, a
for i in range(len(shorter), len(larger)):
if carry != '0':
r, carry = add_digit(larger[i], carry)
result += r
else:
result += larger[i]
if carry != '0':
result += carry
return result[::-1]
def add_digit(digit1, digit2, carry=None):
if carry is None:
carry = '0'
d1, d2, c = int(digit1), int(digit2), int(carry)
s = d1 + d2 + c
return str(s%2), str(s//2)
According to an online judge, the performance for the first implementation is better in terms of time. However, I find the first implementation to be a bit too verbose because I always have to make both the strings of the same size.
- What is the time complexity of creating a new string of length
n? I would like to know what are the corresponding space and time complexities for these implementations and how can I improve on the code. - What are the tradeoffs between the implementations and when should I not use a particular one of them? For example, I should use the 2nd implementation in favour of the 1st when the size of input strings will differ considerably on the general.
bin(int(a, 2) + int(b, 2))[2:]will be faster, more readable and more pythonic.