Saturday, September 30, 2023
HomeSoftware EngineeringHow you can do Binary Addition in Python

How you can do Binary Addition in Python


The problem

Implement a operate that provides two numbers collectively and returns their sum in binary. The conversion will be completed earlier than or after the addition.

The binary quantity returned must be a string.

Examples:

add_binary(1, 1) == "10" (1 + 1 = 2 in decimal or 10 in binary)
add_binary(5, 9) == "1110" (5 + 9 = 14 in decimal or 1110 in binary)

The answer in Python code

There are a number of methods to unravel an int to binary string downside in Python.

Possibility 1:

def add_binary(a,b):
    return "{0:b}".format(a+b)

Possibility 2:

def add_binary(a,b):
    return bin(a+b)[2:]

Possibility 3:

def add_binary(a, b):
    return format(a + b, 'b')

Check instances to validate our resolution

import check
from resolution import add_binary

@check.describe("Mounted Assessments")
def fixed_tests():
    @check.it('Fundamental Check Instances')
    def basic_test_cases():
        check.assert_equals(add_binary(1,1),"10")
        check.assert_equals(add_binary(0,1),"1")
        check.assert_equals(add_binary(1,0),"1")
        check.assert_equals(add_binary(2,2),"100")
        check.assert_equals(add_binary(51,12),"111111")
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments