How to do Binary Addition in Python

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)
Code language: Python (python)

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)
Code language: Python (python)

Option 2:

def add_binary(a,b): return bin(a+b)[2:]
Code language: Python (python)

Option 3:

def add_binary(a, b): return format(a + b, 'b')
Code language: Python (python)

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")
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments