Open In App
Related Articles

Add n binary strings

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given n binary strings, return their sum (also a binary string).

Examples:  

Input:  arr[] = ["11", "1"]
Output: "100"
Input : arr[] = ["1", "10", "11"]
Output : "110"

Approach 1:

Algorithm 

  1. Initialize the ‘result’ as an empty string. 
  2. Traverse the input from i = 0 to n-1.
  3. For each i, add arr[i] to the ‘result’. How to add ‘result’ and arr[i]? Start from the last characters of the two strings and compute the digit sum one by one. If the sum becomes more than 1, then store carry for the next digit. Make this sum as the ‘result’.
  4. The value of ‘result’ after traversing the entire input is the final answer.  

Implementation:

C++

// C++ program to add n binary strings
#include <bits/stdc++.h>
using namespace std;
 
// This function adds two binary strings and return
// result as a third string
string addBinaryUtil(string a, string b)
{
    string result = ""; // Initialize result
    int s = 0; // Initialize digit sum
 
    // Traverse both strings starting from last
    // characters
    int i = a.size() - 1, j = b.size() - 1;
    while (i >= 0 || j >= 0 || s == 1) {
 
        // Compute 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;
}
 
// function to add n binary strings
string addBinary(string arr[], int n)
{
    string result = "";
    for (int i = 0; i < n; i++)
        result = addBinaryUtil(result, arr[i]);
    return result;
}
 
// Driver program
int main()
{
    string arr[] = { "1", "10", "11" };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << addBinary(arr, n) << endl;
    return 0;
}

                    

Java

// Java program to add n binary strings
class GFG
{
 
    // This function adds two binary
    // strings and return result as
    // a third string
    static String addBinaryUtil(String a, String b)
    {
        String result = ""; // Initialize result
        int s = 0; // Initialize digit sum
 
        // Traverse both strings starting
        // from last characters
        int i = a.length() - 1, j = b.length() - 1;
        while (i >= 0 || j >= 0 || s == 1)
        {
 
            // Compute 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 = s % 2 + result;
 
            // Compute carry
            s /= 2;
 
            // Move to next digits
            i--;
            j--;
        }
        return result;
    }
 
    // function to add n binary strings
    static String addBinary(String arr[], int n)
    {
        String result = "";
        for (int i = 0; i < n; i++)
        {
            result = addBinaryUtil(result, arr[i]);
        }
        return result;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String arr[] = {"1", "10", "11"};
        int n = arr.length;
        System.out.println(addBinary(arr, n));
    }
}
 
// This code is contributed by Rajput-JI

                    

Python3

# Python3 program to add n binary strings
 
# This function adds two binary strings and
# return result as a third string
def addBinaryUtil(a, b):
     
    result = ""; # Initialize result
    s = 0;       # Initialize digit sum
 
    # Traverse both strings
    # starting from last characters
    i = len(a) - 1;
    j = len(b) - 1;
    while (i >= 0 or j >= 0 or s == 1):
 
        # Compute sum of last digits and carry
        s += (ord(a[i]) - ord('0')) if(i >= 0) else 0;
        s += (ord(b[j]) - ord('0')) if(j >= 0) else 0;
 
        # If current digit sum is 1 or 3,
        # add 1 to result
        result = chr(s % 2 + ord('0')) + result;
 
        # Compute carry
        s //= 2;
 
        # Move to next digits
        i -= 1;
        j -= 1;
 
    return result;
 
# function to add n binary strings
def addBinary(arr, n):
    result = "";
    for i in range(n):
        result = addBinaryUtil(result, arr[i]);
    return result;
 
# Driver code
arr = ["1", "10", "11"];
n = len(arr);
print(addBinary(arr, n));
     
# This code is contributed by mits

                    

C#

// C# program to add n binary strings
using System;
 
class GFG
{
     
    // This function adds two binary
    // strings and return result as
    // a third string
    static String addBinaryUtil(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)
        {
 
            // Compute 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 = s % 2 + result;
 
            // Compute carry
            s /= 2;
 
            // Move to next digits
            i--;
            j--;
        }
        return result;
    }
 
    // function to add n binary strings
    static String addBinary(String []arr, int n)
    {
        String result = "";
        for (int i = 0; i < n; i++)
        {
            result = addBinaryUtil(result, arr[i]);
        }
        return result;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String []arr = {"1", "10", "11"};
        int n = arr.Length;
        Console.WriteLine(addBinary(arr, n));
    }
}
 
// This code is contributed by 29AjayKumar

                    

Javascript

<script>
 
// Javascript program to add n binary strings
 
// This function adds two binary strings and return
// result as a third string
function addBinaryUtil(a, b)
{
    var result = ""; // Initialize result
    var s = 0; // Initialize digit sum
 
    // Traverse both strings starting from last
    // characters
    var i = a.length - 1, j = b.length - 1;
    while (i >= 0 || j >= 0 || s == 1) {
 
        // Compute sum of last digits and carry
        s += ((i >= 0) ? a.charCodeAt(i) - '0'.charCodeAt(0) : 0);
        s += ((j >= 0) ? b.charCodeAt(j) - '0'.charCodeAt(0) : 0);
 
        // If current digit sum is 1 or 3,
        // add 1 to result
        result = String.fromCharCode((s % 2 ==1 ?1:0) +
                                     '0'.charCodeAt(0)) + result;
 
        // Compute carry
        s = parseInt(s/2);
 
        // Move to next digits
        i--;
        j--;
    }
    return result;
}
 
// function to add n binary strings
function addBinary(arr, n)
{
    var result = "";
    for (var i = 0; i < n; i++)
        result = addBinaryUtil(result, arr[i]);
    return result;
}
 
// Driver program
var arr = ["1", "10", "11"];
var n = arr.length;
document.write( addBinary(arr, n));
 
</script>

                    

PHP

<?php
// PHP program to add n binary strings
 
// This function adds two binary strings and return
// result as a third string
function addBinaryUtil($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)
    {
 
        // Compute 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;
}
 
// function to add n binary strings
function addBinary($arr, $n)
{
    $result = "";
    for ($i = 0; $i < $n; $i++)
        $result = addBinaryUtil($result, $arr[$i]);
    return $result;
}
 
// Driver code
    $arr = array( "1", "10", "11" );
    $n = count($arr);
    echo addBinary($arr, $n)."\n";
     
// This code is contributed by mits
?>

                    

Output
110











Complexity Analysis:

  • Time complexity: O(n) 
  • Auxiliary Space: O(n)

Approach 2:  

By converting the binary strings to decimal numbers.

Here’s a step-by-step explanation of the approach:

  1. Initialize a variable sum to store the sum of the decimal numbers converted from the binary strings.
  2. Loop through each binary string in the array:
    1. Initialize a variable num to store the decimal number converted from the current binary string.
    2. Loop through each character in the current binary string from right to left:
    3. If the current character is ‘1’, add 2 raised to the power of its position from right to num.
    4. Add num to sum.
  3.  Initialize an empty string result to store the binary representation of sum.
  4. While sum is greater than 0:
    1. If sum is even, prepend “0” to result, otherwise prepend “1”.
    2. Divide sum by 2.
  5. Return result.

C++

#include <iostream>
#include <string>
#include <cmath>
 
using namespace std;
 
string addBinary(string arr[], int n)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        int num = 0;
        for (int j = arr[i].size() - 1; j >= 0; j--)
            if (arr[i][j] == '1')
                num += pow(2, arr[i].size() - j - 1);
        sum += num;
    }
    string result = "";
    while (sum > 0)
    {
        result = (sum % 2 == 0 ? "0" : "1") + result;
        sum /= 2;
    }
    return result;
}
 
int main()
{
    string arr[] = { "1", "10", "11" };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << addBinary(arr, n) << endl;
    return 0;
}

                    

Java

import java.io.*;
import java.math.BigInteger;
 
public class GFG {
    static String addBinary(String[] arr) {
        BigInteger sum = BigInteger.ZERO;
 
        // Loop through each binary number in the input array
        for (String binaryStr : arr) {
            // Convert the binary number to its decimal equivalent using BigInteger
            BigInteger num = new BigInteger(binaryStr, 2);
 
            // Add the decimal value of the binary number to the total sum
            sum = sum.add(num);
        }
 
        // Convert the sum to a binary string representation
        return sum.toString(2);
    }
 
    // Example usage
    public static void main(String[] args) {
        String[] arr = {"1", "10", "11"};
        System.out.println(addBinary(arr));
    }
}

                    

Python3

def addBinary(arr):
    # Initialize a variable to store the sum of binary numbers
    sum = 0
 
    # Loop through each binary number in the input array
    for i in range(len(arr)):
        # Initialize a variable to store the decimal value of the binary number
        num = 0
 
        # Convert the binary number to its decimal equivalent
        for j in range(len(arr[i]) - 1, -1, -1):
            if arr[i][j] == '1':
                num += 2**(len(arr[i]) - j - 1)
 
        # Add the decimal value of the binary number to the total sum
        sum += num
 
    # Initialize an empty string to store the final result
    result = ''
 
    # Convert the sum to a binary string representation
    while sum > 0:
        result = ('0' if sum % 2 == 0 else '1') + result
        sum = sum // 2
 
    # Return the final binary string representation
    return result
 
 
# Driver code
arr = ['1', '10', '11']
print(addBinary(arr))
# THIS CODE IS CONTRIBUTED CHANDAN AGARWAL

                    

C#

using System;
 
class GFG
{
    static string addBinary(string[] arr)
    {
        // Initialize a variable to store the sum of binary numbers
        int sum = 0;
 
        // Loop through each binary number in the input array
        foreach (string binNum in arr)
        {
            // Initialize a variable to store the decimal value of the binary number
            int num = 0;
 
            // Convert the binary number to its decimal equivalent
            for (int j = binNum.Length - 1; j >= 0; j--)
            {
                if (binNum[j] == '1')
                {
                    num += (int)Math.Pow(2, binNum.Length - j - 1);
                }
            }
 
            // Add the decimal value of the binary number to the total sum
            sum += num;
        }
 
        // Initialize an empty string to store the final result
        string result = "";
 
        // Convert the sum to a binary string representation
        while (sum > 0)
        {
            result = (sum % 2 == 0 ? '0' : '1') + result;
            sum /= 2;
        }
 
        // Return the final binary string representation
        return result;
    }
 
    static void Main(string[] args)
    {
        string[] arr = { "1", "10", "11" };
        Console.WriteLine(addBinary(arr));
    }
}

                    

Javascript

function addBinary(arr) {
    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
        let num = 0;
        for (let j = arr[i].length - 1; j >= 0; j--) {
            if (arr[i][j] === '1') {
                num += Math.pow(2, arr[i].length - j - 1);
            }
        }
        sum += num;
    }
    let result = '';
    while (sum > 0) {
        result = (sum % 2 === 0 ? '0' : '1') + result;
        sum = Math.floor(sum / 2);
    }
    return result;
}
 
// Driver code
const arr = ['1', '10', '11'];
console.log(addBinary(arr));

                    

PHP

<?php
 
function addBinary($arr) {
    // Initialize a variable to store the sum of binary numbers
    $sum = 0;
 
    // Loop through each binary number in the input array
    foreach ($arr as $binaryNumber) {
        // Initialize a variable to store the decimal value of the binary number
        $num = 0;
 
        // Convert the binary number to its decimal equivalent
        for ($j = strlen($binaryNumber) - 1; $j >= 0; $j--) {
            if ($binaryNumber[$j] == '1') {
                $num += 2 ** (strlen($binaryNumber) - $j - 1);
            }
        }
 
        // Add the decimal value of the binary number to the total sum
        $sum += $num;
    }
 
    // Initialize an empty string to store the final result
    $result = '';
 
    // Convert the sum to a binary string representation
    while ($sum > 0) {
        $result = ($sum % 2 == 0 ? '0' : '1') . $result;
        $sum = (int)($sum / 2);
    }
 
    // Return the final binary string representation
    return $result;
}
 
// Driver code
$arr = ['1', '10', '11'];
echo addBinary($arr);
 
?>

                    

Output
110











Time Complexity: O(N*K)
Auxiliary Space: O(1)

Explanation:

The time complexity of this approach is O(nk), where n is the number of binary strings and k is the maximum length of a binary string in the array. This is because we need to loop through each binary string and each character in the binary strings.

The auxiliary space complexity of this approach is O(1), as we only use a constant amount of extra space to store variables such as sum, num, and result.



Last Updated : 08 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads