How to do Binary Addition in Python

0 min read 132 words

The challenge

Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before or after the addition.

The binary number returned should 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 solution in Python code

There are multiple ways to solve an int to binary string problem in Python.

Option 1:

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

Option 2:

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

Option 3:

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

Test cases to validate our solution

import test
from solution import add_binary

@test.describe("Fixed Tests")
def fixed_tests():
    @test.it('Basic Test Cases')
    def basic_test_cases():
        test.assert_equals(add_binary(1,1),"10")
        test.assert_equals(add_binary(0,1),"1")
        test.assert_equals(add_binary(1,0),"1")
        test.assert_equals(add_binary(2,2),"100")
        test.assert_equals(add_binary(51,12),"111111")
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags