简体   繁体   中英

Sum binary numbers using selective structures and loops? PYTHON

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM