Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Subtract Two Binary Numbers
Next article icon

Python program to add two binary numbers

Last Updated : 11 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two binary numbers, write a Python program to compute their sum.

Examples:

Input:  a = "11", b = "1" Output: "100"  Input: a = "1101", b = "100" Output: 10001

Approach:

  • Naive Approach: The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum becomes more than 1, then store carry for the next digits.
  • Using inbuilt function: Calculate the result by using the inbuilt bin() and int() function.

Method 1: Naive Approach: 

The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum becomes more than 1, then store carry for the next digits.

Python3




# Python program to add two binary numbers.
 
# Driver code
# Declaring the variables
a = "1101"
b = "100"
max_len = max(len(a), len(b))
a = a.zfill(max_len)
b = b.zfill(max_len)
 
# Initialize the result
result = ''
 
# Initialize the carry
carry = 0
 
# Traverse the string
for i in range(max_len - 1, -1, -1):
    r = carry
    r += 1 if a[i] == '1' else 0
    r += 1 if b[i] == '1' else 0
    result = ('1' if r % 2 == 1 else '0') + result
 
    # Compute the carry.
    carry = 0 if r < 2 else 1
 
if carry != 0:
    result = '1' + result
 
print(result.zfill(max_len))
 
 
Output
10001

Time complexity : O(n)
Space Complexity : O(n) 

Method 2: Using inbuilt functions:

We will first convert the binary string to a decimal using int() function in python. The int() function in Python and Python3 converts a number in the given base to decimal. Then we will add it and then again convert it into a binary number using bin() function.

Example 1:

Python3




# Python program to add two binary numbers.
 
# Driver code
# Declaring the variables
a = "1101"
b = "100"
 
# Calculating binary value using function
sum = bin(int(a, 2) + int(b, 2))
 
# Printing result
print(sum[2:])
 
 
Output
10001

Time Complexity: O(n)
Auxiliary Space: O(n)

Example 2:

Python3




# Python program to add two binary numbers.
 
# Driver code
if __name__ == "__main__" :
 
    # Declaring the variables
    a = "1101"
    b = "100"
     
    # Calculating binary sum by using bin() and int()
    binary_sum = lambda a,b : bin(int(a, 2) + int(b, 2))
     
    # calling binary_sum lambda function
    print(binary_sum(a,b)[2:])
     
    # This code is contributed by AnkThon
 
 
Output
10001

Time complexity :  O(1)
Space Complexity : O(1)

Method: Using “add” operator 

Python3




from operator import*
num1="1101"
num2="100"
print(bin(add(int(num1,2),int(num2,2))))
 
 

Output 

0b10001

Time complexity :  O(n)
Space Complexity : O(1)

METHOD 3:Using loop

APPROACH:

The given Python code takes two binary numbers as strings, ‘a’ and ‘b’, and returns their sum as a binary string ‘result’. The addition of two binary numbers is performed using the standard column-wise addition algorithm, in which digits are added from right to left with carrying over the digits when the sum exceeds 1. The algorithm continues until all digits of both numbers are added.

ALGORITHM:

1. Initialize an empty string ‘result’ and a carry variable to 0.
2. Set the index of the last digit of ‘a’ and ‘b’ strings to ‘i’ and ‘j’, respectively.
3. Repeat the following while loop until ‘i’ or ‘j’ is less than 0 or there is a carry:
a. Initialize the ‘total’ variable to ‘carry’
b. If ‘i’ is greater than or equal to 0, add the ‘i’-th digit of ‘a’ to ‘total’ and decrement ‘i’.
c. If ‘j’ is greater than or equal to 0, add the ‘j’-th digit of ‘b’ to ‘total’ and decrement ‘j’.
d. Calculate the value of the current digit in the result as ‘total % 2’ and add it to the left of ‘result’.
e. Update the value of the carry as ‘total // 2’.
4. If there is still a carry after the while loop, add it to the left of ‘result’.
5. Return the ‘result’ string.

Python3




a = "1101"
b = "100"
result = ""
carry = 0
i, j = len(a)-1, len(b)-1
while i >= 0 or j >= 0 or carry:
    total = carry
    if i >= 0:
        total += int(a[i])
        i -= 1
    if j >= 0:
        total += int(b[j])
        j -= 1
    result = str(total % 2) + result
    carry = total // 2
print(result)
 
 
Output
10001

Time Complexity:
The algorithm iterates over each digit of both numbers once, so the time complexity of the algorithm is O(n), where ‘n’ is the maximum length of the input strings.

Space Complexity:
The algorithm uses only a constant amount of extra space to store variables like ‘result’, ‘carry’, ‘i’, and ‘j’, so the space complexity of the algorithm is O(1).



Next Article
Python Program to Subtract Two Binary Numbers
author
aditya_taparia
Improve
Article Tags :
  • Python
  • Python Programs
  • school-programming
Practice Tags :
  • python

Similar Reads

  • Python Program to Multiply Two Binary Numbers
    Given two binary numbers, and the task is to write a Python program to multiply both numbers. Example: firstnumber = 110 secondnumber = 10 Multiplication Result = 1100 We can multiply two binary numbers in two ways using python, and these are: Using bin() functions andWithout using pre-defined funct
    2 min read
  • Python Program to Subtract Two Binary Numbers
    We are given two binary numbers, num1 and num2 and we have to subtract these two binary numbers and return the result. In this article, we will see how we can subtract two binary numbers in Python. Examples: Input: a = "1110" , b = "0110"Output: "1000"Explanation: We can see that when "1110" is subt
    3 min read
  • Python Program to add two hexadecimal numbers
    Given two hexadecimal numbers, write a Python program to compute their sum. Examples: Input: a = "01B", b = "378" Output: 393 Explanation: B (11 in decimal) + 8 = 19 (13 in hex), hence addition bit = 3, carry = 1 1 + 7 + 1 (carry) = 9, hence addition bit = 9, carry = 0 0 + 3 + 0 (carry) = 3, hence a
    6 min read
  • Python program to add two Octal numbers
    Given two octal numbers, the task is to write a Python program to compute their sum. Examples: Input: a = "123", b = "456" Output: 601 Input: a = "654", b = "321" Output: 1175Approach: To add two octal values in python we will first convert them into decimal values then add them and then finally aga
    2 min read
  • Python program to add two matrices
    Prerequisite : Arrays in Python, Loops, List Comprehension Program to compute the sum of two matrices and then print it in Python. We can perform matrix addition in various ways in Python. Here are a two of them. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Outp
    2 min read
  • Python program to convert ASCII to Binary
    We are having a string s="Hello" we need to convert the string to its ASCII then convert the ASCII to Binary representation so that the output becomes : 01001000 01100101 01101100 01101100 0110111. To convert an ASCII string to binary we use ord() to get the ASCII value of each character and format(
    2 min read
  • Python program to convert binary to ASCII
    In this article, we are going to see the conversion of Binary to ASCII in the Python programming language. There are multiple approaches by which this conversion can be performed that are illustrated below: Method 1: By using binascii module Binascii helps convert between binary and various ASCII-en
    3 min read
  • How to Add Two Numbers in Python
    The task of adding two numbers in Python involves taking two input values and computing their sum using various techniques . For example, if a = 5 and b = 7 then after addition, the result will be 12. Using the "+" Operator+ operator is the simplest and most direct way to add two numbers . It perfor
    5 min read
  • Python3 Program to Rotate bits of a number
    Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. In the left rotation, the bits that fall off at the left end are put back at the right end. In the right rotation, the bits that fall off at th
    3 min read
  • Python program to convert Base 4 system to binary number
    Given a base 4 number N, the task is to write a python program to print its binary equivalent. Conversion Table: Examples: Input : N=11002233 Output : 101000010101111 Explanation : From that conversion table we changed 1 to 01, 2 to 10 ,3 to 11 ,0 to 00.Input : N=321321 Output: 111001111001Method 1:
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences