Addition of Two Binary Numbers | Function | Python
Addition of Two Binary Numbers entered by the user in Python Programming Language through the concept of Function.
- Coding for the above Program.
- def add_bn(x, y):
- max_len = max(len(x), len(y))
- x = x.zfill(max_len)
- y = y.zfill(max_len)
- result = ''
- carry = 0
- for i in range(max_len - 1, -1, -1):
- r = carry
- r += 1 if x[i] == '1' else 0
- r += 1 if y[i] == '1' else 0
- result = ('1' if r % 2 == 1 else '0') + result
- carry = 0 if r < 2 else 1
- if carry !=0 : result = '1' + result
- return result.zfill(max_len)
- n1=input("Enter First Binary Number=")
- n2=input("Enter Second Binary Number=")
- print(f"Addition of {n1} and {n2} is {add_bn(n1, n2)}")
- Output of the Temperature Conversion Program.
Output of Addition of Binary Numbers in Python |
Notes:
- If you have any problem related to this program. Please do comment your Problem or Mail us.
- For illustrating the any concept you can comment by line number.
- Thank you! For more programs do regular visit to Coding 4 Programming.
Comments
Post a Comment