-1

I need to sum 2 binary numbers (max len 8 and min 1) using only selective structures (if, elif, else) and loops (for, while).

You need to know in the binary sum:

0 + 1 = 1
1 + 0 = 1
1 + 1 = 0 (with carry 1) 

The result must be the sum of these two numbers. Also, show the partial results that are generated by adding two digits and carrying

I know you could easily do this, but the idea is use only selective structure and loops.

a = input("first binary: ")
b = input("second binary: ")
c = bin(int(a,2) + int(b,2))

OUTPUT example:

sum:

 11001011
 10001011
=========
101010110

Partial results:

digit = 0 Carry = 1
digit = 1 Carry = 1
digit = 1 Carry = 0
digit = 0 Carry = 1
digit = 1 Carry = 0
digit = 0 Carry = 0
digit = 1 Carry = 0
digit = 0 Carry = 1

This question is different to the others made, because none of the others answer just using selective and repetitive structures

Y4RD13
  • 937
  • 1
  • 16
  • 42
  • 1
    It seems that this is a homework question. If this is true, please include all relevant work you have done already in the question. See [this](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions). – iz_ Aug 01 '19 at 05:52
  • Possible duplicate of [Need help in adding binary numbers in python](https://stackoverflow.com/questions/21420447/need-help-in-adding-binary-numbers-in-python) – sahasrara62 Aug 01 '19 at 06:01

1 Answers1

1

If you are allowed to use slicing, you can do this:

num1 = '11001011'    # you can replace these with input() calls
num2 = '10001011'
# reverse the strings as we will be doing the operations from the left, otherwise you will need to pass reversed strings in the for loop iterator
num1 = num1[::-1]
num2 = num2[::-1]
# to tackle uneven lengths you can pad with 0s
if len(num2)>len(num1):
    padding = len(num2) - len(num1)
    num1 = num1 + '0'*padding
else:
    padding = len(num2) - len(num1)
    num1 = num1 + '0'*padding
currentresult = ''
nextdigit = 0
# iterate over two numbers
for i, j in zip(num1,num2):   # if you are not allowed to use zip, you can use two nested loops one for num1 and one for num2, and add an if condition to do the operations only when i == j
    i = int(i) + nextdigit
    if int(i) + int(j) == 3:
        # case where current bits are 1 and 1, and carry from the last addition is 1
        carry = 1
        digit = 1
    elif int(i)+int(j) == 2:
        carry = 1
        digit = 0
    elif int(i)+int(j) == 1:
        carry = 0
        digit = 1
    else:
        carry = 0
        digit = 0
    currentresult += str(digit)
    nextdigit = carry
# add next digit (if in case the carry from the last bits are 1)
if nextdigit == 1:
    currentresult += str(nextdigit)
# reverse the strings as we got the result in reverse
finalresult = currentresult[::-1]
print(finalresult)
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52