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:
1
2
|
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:
1
2
|
def add_binary(a,b):
return "{0:b}".format(a+b)
|
Option 2:
1
2
|
def add_binary(a,b):
return bin(a+b)[2:]
|
Option 3:
1
2
|
def add_binary(a, b):
return format(a + b, 'b')
|
Test cases to validate our solution
1
2
3
4
5
6
7
8
9
10
11
12
|
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")
|