Sunday, April 14, 2024
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

@check.describe("Mounted Assessments")
def fixed_tests():
@check.it('Fundamental Check Instances')
def basic_test_cases():
``````
RELATED ARTICLES