Python Practice › Function Programs › Program 34
Add two binary numbers
Write a Python function to add two binary numbers given as strings.
Input
"1011", "111"
Output
10010
Approach
- Convert with
int(x, 2), add, convert back withbin().
Solution
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.