use Python: 1. Binary Addition (3 points) Addition is a common arithmetic operat
ID: 3812046 • Letter: U
Question
use Python:
1. Binary Addition (3 points) Addition is a common arithmetic operation, and it can be performed on numbers in any base. In fact, binary addition is simpler than base 10 addition because there are fewer rules. Like base 10 addition, binary addition works from right-to-left, adding one pair or column of digits at a time, according to the following rules: 0 0-0 0 1 1 1 0-1 1 1 0, plus a carry bit of 1 (for the next column) 1 1 2, and 2 is 10 in binary If you have three 1s to add (1 1, plus a carry bit of 1 from the previous column), the sum is 1, with a carry bit of 1 (1 1 1 33, and 3 is 11 in binary). For example, consider the following addition problem (11 11, in base 10): 1011 +1011 We start by adding the rightmost column. 1 plus 1 gives us 0, plus a carry bit of 1 1011 +1011 The second column has two 1s, plus a carry bit of 1. 1 1 1 equals 1, plus a(nother) carry bit of 1 1011 +1011 10Explanation / Answer
def addBinary(first,second)
s1 = first
s2 = second
Length_MAX = max(len(s1), len(s2))
s1 = s1.zfill(Length_MAX)
s2 = s2.zfill(Length_MAX)
result = ''
carry = 0
i = Length_MAX - 1
while(i >= 0):
s = int(s1[i]) + int(s2[i])
if s == 2: #1+1
if carry == 0:
carry = 1
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
elif s == 1: # 1+0
if carry == 1:
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
else: # 0+0
if carry == 1:
result = "%s%s" % (result, '1')
carry = 0
else:
result = "%s%s" % (result, '0')
i = i - 1;
if carry>0:
result = "%s%s" % (result, '1')
return result[::-1]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.