Open In App

Add two binary strings

Last Updated : 24 Oct, 2024
Comments
Improve
Suggest changes
54 Likes
Like
Report

Given two binary strings s1 and s2, the task is to return their sum.The input strings may contain leading zeros but the output string should not have any leading zeros.

Example: 

Input: s1 = "1101", s2 = "111"
Output: "10100"
Explanation:

Add-two-binary-strings-using-Bit-by-Bit-addition

Input: s1 = "00100", s2 = "010"
Output: "110"

Bit-by-bit addition with carry - O(n + m) Time and O(1) Space

The idea is to first trim the leading zeros in the input strings. Now, start from the last characters of the strings and compute the digit sum one by one. If the sum becomes more than 1, then store carry for the next digits. Also consider this carry while calculating the digit sum. After calculating the sum, if an additional carry is generated, prepend a '1' of the result.

C++
Java Python3 C# JavaScript

Output
10100

Time Complexity: O(n + m), for traversing the strings.
Auxiliary Space: O(n), for result array as strings are immutable in most of language and O(1) in C++ where strings are mutable.

Related Articles:

 


Add two binary strings
Visit Course explore course icon

Similar Reads