Skip to content

Instantly share code, notes, and snippets.

@svalleru
Created May 18, 2015 21:36
Show Gist options
  • Save svalleru/21fdde6dd75f9150dc57 to your computer and use it in GitHub Desktop.
Save svalleru/21fdde6dd75f9150dc57 to your computer and use it in GitHub Desktop.
BinarySum
# Given two input binary strings, calculate their sum
s1 = '1'
s2 = '1101'
s1l = list(s1)[::-1]
s2l = list(s2)[::-1]
# Padding
if len(s1l) < len(s2l):
s1l = s1l + ['0'] * (len(s2l) - len(s1l))
elif len(s2l) < len(s1l):
s2l = s2l + ['0'] * (len(s1l) - len(s2l))
s = [] # for sum bits
c = '0' # carry bit
print zip(s1l, s2l)
for s1b, s2b in zip(s1l, s2l):
if (s1b == '1' and s2b == '0') or (s1b == '0' and s2b == '1'):
if c == '0':
s.append('1')
else:
s.append('0')
elif s1b == '0' and s2b == '0':
if c == '0':
s.append('0')
else:
s.append('1')
c = '0'
else: # both incoming bits are 1's
if c == '0':
s.append('0')
c = 1
else:
s.append('1')
if c == 1:
s.append(1)
print 'Binary sum of {0} and {1} is: {2}'.format(s1, s2, ''.join(s[::-1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment