Program to add two binary strings

30 Jun, 2022
Given two binary strings, return their sum (also a binary string).
Example: 
Input:  a = "11", b = "1"
Output: "100" 
We strongly recommend you to minimize your browser and try this yourself first 
The idea is to start from the last characters of two strings and compute the digit sum one by one. If the sum becomes more than 1, then store carry for the next digits. 
C
Java
Python3
C#
PHP
Javascript
// C++ program to add two binary strings#include <bits/stdc++.h>using namespace std; // This function adds two binary strings and return// result as a third stringstring addBinary(string A, string B){    // If the length of string A is greater than the length    // of B then just swap the string by calling the    // same function and make sure to return the function    // otherwise recursion will occur which leads to    // calling the same function twice    if (A.length() > B.length())        return addBinary(B, A);     // Calculating the difference between the length of the    // two strings.    int diff = B.length() - A.length();     // Initialise the padding string which is used to store    // zeroes that should be added as prefix to the string    // which has length smaller than the other string.    string padding;    for (int i = 0; i < diff; i++)        padding.push_back('0');     A = padding + A;    string res;    char carry = '0';     for (int i = A.length() - 1; i >= 0; i--) {        // This if condition solves 110 111 possible cases        if (A[i] == '1' && B[i] == '1') {            if (carry == '1')                res.push_back('1'), carry = '1';            else                res.push_back('0'), carry = '1';        }        // This if condition solves 000 001 possible cases        else if (A[i] == '0' && B[i] == '0') {            if (carry == '1')                res.push_back('1'), carry = '0';            else                res.push_back('0'), carry = '0';        }        // This if condition solves 100 101 010 011 possible        // cases        else if (A[i] != B[i]) {            if (carry == '1')                res.push_back('0'), carry = '1';            else                res.push_back('1'), carry = '0';        }    }     // If at the end their is carry then just add it to the    // result    if (carry == '1')        res.push_back(carry);    // reverse the result    reverse(res.begin(), res.end());     // To remove leading zeroes    int index = 0;    while (index + 1 < res.length() && res[index] == '0')        index++;    return (res.substr(index));} // Driver programint main(){    string a = "1101", b = "100";    cout << addBinary(a, b) << endl;    return 0;}
// java program to add// two binary strings public class GFG {     // This function adds two    // binary strings and return    // result as a third string    static String addBinary(String a, String b)    {             //If the inputs are 0        if(a.charAt(0) == '0' && b.charAt(0) == '0'){             return "0";        }        // Initialize result        StringBuilder result = new StringBuilder("");                 // Initialize digit sum        int s = 0;                 // Traverse both strings starting        // from last characters        int i = a.length() - 1, j = b.length() - 1;        while (i >= 0 || j >= 0 || s == 1)        {                         // Comput sum of last            // digits and carry            s += ((i >= 0)? a.charAt(i) - '0': 0);            s += ((j >= 0)? b.charAt(j) - '0': 0);             // If current digit sum is            // 1 or 3, add 1 to result            result.append((char)(s % 2 + '0'));             // Compute carry            s /= 2;             // Move to next digits            i--; j--;        }                 // Remove leading zeros, if any          int start = result.length()-1;                 while(start >=0 && result.charAt(start) == '0') {            start--;        }                 if(start != result.length()-1) {            result.delete(start+1,result.length());        }                 return result.reverse().toString();    }     //Driver code    public static void main(String args[])    {        String a = "1101", b="100";                 System.out.print(addBinary(a, b));    }} // This code is contributed by Sam007.
# Python Solution for above problem: # This function adds two binary# strings return the resulting stringdef add_binary_nums(x, y):        max_len = max(len(x), len(y))         x = x.zfill(max_len)        y = y.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 x[i] == '1' else 0            r += 1 if y[i] == '1' else 0            result = ('1' if r % 2 == 1 else '0') + result            carry = 0 if r < 2 else 1     # Compute the carry.                 if carry !=0 : result = '1' + result         return result.zfill(max_len) # Driver codeprint(add_binary_nums('1101', '100')) # This code is contributed# by Anand Khatri
// C# program to add// two binary stringsusing System; class GFG {         // This function adds two    // binary strings and return    // result as a third string    static string addBinary(string a,                            string b)    {                 // Initialize result        string result = "";                 // Initialize digit sum        int s = 0;                 // Traverse both strings starting        // from last characters        int i = a.Length - 1, j = b.Length - 1;        while (i >= 0 || j >= 0 || s == 1)        {                         // Comput sum of last            // digits and carry            s += ((i >= 0)? a[i] - '0': 0);            s += ((j >= 0)? b[j] - '0': 0);             // If current digit sum is            // 1 or 3, add 1 to result            result = (char)(s % 2 + '0') + result;             // Compute carry            s /= 2;             // Move to next digits            i--; j--;        }    return result;    }     // Driver Code   public static void Main(){    string a = "1101", b="100";    Console.Write( addBinary(a, b));}} // This code is contributed by Sam007
<?php// PHP program to add two binary strings // This function adds two binary strings// and return result as a third stringfunction addBinary($a, $b){    $result = ""; // Initialize result    $s = 0;     // Initialize digit sum     // Traverse both strings starting    // from last characters    $i = strlen($a) - 1;    $j = strlen($b) - 1;    while ($i >= 0 || $j >= 0 || $s == 1)    {        // Comput sum of last digits and carry        $s += (($i >= 0)? ord($a[$i]) -                          ord('0'): 0);        $s += (($j >= 0)? ord($b[$j]) -                          ord('0'): 0);         // If current digit sum is 1 or 3,        // add 1 to result        $result = chr($s % 2 + ord('0')) . $result;         // Compute carry        $s = (int)($s / 2);         // Move to next digits        $i--; $j--;    }    return $result;} // Driver Code$a = "1101";$b = "100";echo addBinary($a, $b); // This code is contributed by mits?>
<script> // Javascript program to add// two binary strings // This function adds two// binary strings and return// result as a third stringfunction addBinary(a, b){         // Initialize result    var result = "";         // Initialize digit sum    var s = 0;             // Traverse both strings starting    // from last characters    var i = a.length - 1, j = b.length - 1;    while (i >= 0 || j >= 0 || s == 1)    {                 // Comput sum of last        // digits and carry        s += ((i >= 0)? a.charAt(i).charCodeAt(0) -        '0'.charCodeAt(0): 0);        s += ((j >= 0)? b.charAt(j).charCodeAt(0) -        '0'.charCodeAt(0): 0);         // If current digit sum is        // 1 or 3, add 1 to result        result = String.fromCharCode(parseInt(s % 2) +        '0'.charCodeAt(0)) + result;         // Compute carry        s = parseInt(s/2);         // Move to next digits        i--; j--;    }     return result;} //Driver codevar a = "1101", b="100"; document.write(addBinary(a, b)); // This code is contributed by Amit Katiyar </script>
10001
Time Complexity: O(max(L1, L2)), where L1 and L2 are the lengths of strings a and b respectively. Auxiliary Space: O(max(L1, L2)), where L1 and L2 are the lengths of strings a and b respectively. 
Add two binary strings | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersAdd two binary strings | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:54•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=TraAvM7JxL4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Sam007
anandkhatri
Mithun Kumar
shubham_singh
Akanksha_Rai
amit143katiyar
adityakumar129
rupeswarofficial
sumitgumber28
sweetyty
ankita_saini
shivamanandrj9
hardikkoriintern
sepidehfallah2
Facebook
Microsoft
Mathematical
Strings
Microsoft
Facebook
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
Write a program to reverse an array or string
Reverse a string in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not