Add two binary numbers

EasyFunction Programs · 34 of 39

Write a Python function to add two binary numbers given as strings.

Advertisement
Input
"1011", "111"
Output
10010

Approach

  1. Convert with int(x, 2), add, convert back with bin().

Solution

Python
def add_binary(a, b):    return bin(int(a, 2) + int(b, 2))[2:] print(add_binary("1011", "111"))
Output
10010

Line by line

Line 2

[2:] drops the “0b” prefix.

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs

Leave a Comment