Add n binary strings
Last Updated :
10 Dec, 2024
Improve
Given n binary strings, the task is to find their sum which is also a binary string.
Examples:
Input: arr[] = ["1101", "111"]
Output: "10100"
Explanation:
Input : arr[] = ["1", "10", "11"]
Output : "110"
[Approach] Bit-by-bit addition with carry
A simple idea is to initialise res = "0" and preform addition of each string with res one by one. The value of res after adding all binary strings is the final answer.
For adding res and arr[i], we use the approach used in Add two binary strings.
//Driver Code Starts
// C++ program to add n binary strings
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Function to trim leading zeros from a binary string
//Driver Code Ends
string trimLeadingZeros(const string &s) {
// Find the position of the first '1'
size_t firstOne = s.find('1');
return (firstOne == string::npos) ? "0" : s.substr(firstOne);
}
// Function adds two binary strings
string addTwoBinary(string &s1, string &s2) {
// Trim leading zeros
s1 = trimLeadingZeros(s1);
s2 = trimLeadingZeros(s2);
int n = s1.size();
int m = s2.size();
// swap the strings if s1 is of smaller length
if (n < m) {
return addTwoBinary(s2, s1);
}
int j = m - 1;
int carry = 0;
// Traverse both strings from the end
for (int i = n - 1; i >= 0; i--) {
// Current bit of s1
int bit1 = s1[i] - '0';
int sum = bit1 + carry;
//Driver Code Starts
// If there are remaining bits in s2, add them to the sum
if (j >= 0) {
// Current bit of s2
int bit2 = s2[j] - '0';
sum += bit2;
j--;
}
// Calculate the result bit and update carry
int bit = sum % 2;
carry = sum / 2;
// Update the current bit in s1
s1[i] = (char)(bit + '0');
}
// If there's any carry left, update s1
if (carry > 0) {
s1 = '1' + s1;
}
return s1;
}
// function to add n binary strings
string addBinary(vector<string> &arr) {
string res = "0";
for (int i = 0; i < arr.size(); i++)
res = addTwoBinary(res, arr[i]);
return res;
}
int main() {
vector<string> arr = { "1", "10", "11" };
cout << addBinary(arr);
return 0;
}
//Driver Code Ends
// Java program to add n binary strings
class GfG {
// Function to trim leading zeros from a binary string
static String trimLeadingZeros(String s) {
// Find the position of the first '1'
int firstOne = s.indexOf('1');
return (firstOne == -1) ? "0"
: s.substring(firstOne);
}
// Function to add two binary strings
static String addTwoBinary(String s1, String s2) {
// Trim Leading Zeros
s1 = trimLeadingZeros(s1);
s2 = trimLeadingZeros(s2);
int n = s1.length();
int m = s2.length();
// Swap the strings if s1 is of smaller length
if (n < m) {
return addTwoBinary(s2, s1);
}
int j = m - 1;
int carry = 0;
StringBuilder result = new StringBuilder();
// Traverse both strings from the end
for (int i = n - 1; i >= 0; i--) {
// Current bit of s1
int bit1 = s1.charAt(i) - '0';
int sum = bit1 + carry;
// If there are remaining bits in s2, add them
// to the sum
if (j >= 0) {
// Current bit of s2
int bit2 = s2.charAt(j) - '0';
sum += bit2;
j--;
}
// Calculate the result bit and update carry
int bit = sum % 2;
carry = sum / 2;
// Update the current bit in result
result.append((char)(bit + '0'));
}
// If there's any carry left, update the result
if (carry > 0)
result.append('1');
return result.reverse().toString();
}
// function to add n binary strings
static String addBinary(String arr[]) {
String res = "0";
for (int i = 0; i < arr.length; i++) {
res = addTwoBinary(res, arr[i]);
}
return res;
}
public static void main(String[] args) {
String arr[] = {"1", "10", "11"};
System.out.println(addBinary(arr));
}
}
# Python3 program to add n binary strings
def trimLeadingZeros(s):
# Find the position of the first '1'
firstOne = s.find('1')
return s[firstOne:] if firstOne != -1 else "0"
# function to two binary strings
def addTwoBinary(s1, s2):
# Trim Leading Zeros
s1 = trimLeadingZeros(s1)
s2 = trimLeadingZeros(s2)
n = len(s1)
m = len(s2)
# Swap the strings if s1 is of smaller length
if n < m:
s1, s2 = s2, s1
n, m = m, n
j = m - 1
carry = 0
result = []
# Traverse both strings from the end
for i in range(n - 1, -1, -1):
# Current bit of s1
bit1 = int(s1[i])
bitSum = bit1 + carry
# If there are remaining bits in s2
# add them to the bitSum
if j >= 0:
# Current bit of s2
bit2 = int(s2[j])
bitSum += bit2
j -= 1
# Calculate the result bit and update carry
bit = bitSum % 2
carry = bitSum // 2
# Update the current bit in result
result.append(str(bit))
# If there's any carry left, prepend it to the result
if carry > 0:
result.append('1')
return ''.join(result[::-1])
# function to add n binary strings
def addBinary(arr):
res = "0";
for i in range(len(arr)):
res = addTwoBinary(res, arr[i]);
return res;
if __name__ == '__main__':
arr = ["1", "10", "11"];
n = len(arr);
print(addBinary(arr));
// C# program to add n binary strings
using System;
class GfG {
// Function to trim leading zeros from a binary string
static string trimLeadingZeros(string s) {
// Find the position of the first '1'
int firstOne = s.IndexOf('1');
return (firstOne == -1) ? "0" : s.Substring(firstOne);
}
// function to add two binary strings
static string addTwoBinary(string s1, string s2) {
// Trim leading zeros
s1 = trimLeadingZeros(s1);
s2 = trimLeadingZeros(s2);
int n = s1.Length;
int m = s2.Length;
// Swap the strings if s1 is of smaller length
if (n < m) {
return addTwoBinary(s2, s1);
}
int j = m - 1;
int carry = 0;
char[] result = new char[n];
// Traverse both strings from the end
for (int i = n - 1; i >= 0; i--) {
// Current bit of s1
int bit1 = s1[i] - '0';
int sum = bit1 + carry;
// If there are remaining bits in s2, add them to the sum
if (j >= 0) {
// Current bit of s2
int bit2 = s2[j] - '0';
sum += bit2;
j--;
}
// Calculate the result bit and update carry
int bit = sum % 2;
carry = sum / 2;
// Update the current bit in result
result[i] = (char)(bit + '0');
}
// If there's any carry left, prepend it to the result
if (carry > 0) {
return '1' + new string(result);
}
return new string(result);
}
// function to add n binary strings
static String addBinary(String []arr) {
String res = "0";
for (int i = 0; i < arr.Length; i++) {
res = addTwoBinary(res, arr[i]);
}
return res;
}
static void Main(String[] args) {
String []arr = {"1", "10", "11"};
Console.WriteLine(addBinary(arr));
}
}
// Javascript program to add n binary strings
// Function to trim leading zeros from a binary string
function trimLeadingZeros(s) {
// Find the position of the first '1'
let firstOne = s.indexOf('1');
return (firstOne === -1) ? "0" : s.substring(firstOne);
}
// Function to add two binary strings
function addTwoBinary(s1, s2) {
// Trim leading zeros
s1 = trimLeadingZeros(s1);
s2 = trimLeadingZeros(s2);
let n = s1.length;
let m = s2.length;
// Swap the strings if s1 is of smaller length
if (n < m) {
return addTwoBinary(s2, s1);
}
let j = m - 1;
let carry = 0;
let result = [];
// Traverse both strings from the end
for (let i = n - 1; i >= 0; i--) {
// Current bit of s1
let bit1 = s1[i] - '0';
let sum = bit1 + carry;
// If there are remaining bits in s2, add them to the sum
if (j >= 0) {
// Current bit of s2
let bit2 = s2[j] - '0';
sum += bit2;
j--;
}
// Calculate the result bit and update carry
let bit = sum % 2;
carry = Math.floor(sum / 2);
// Update the current bit in result
result.push(bit);
}
// If there's any carry left, prepend it to the result
if (carry > 0) {
result.push(1);
}
return result.reverse().join('');
}
// Function to add n binary strings
function addBinary(arr) {
var res = "0";
for (var i = 0; i < arr.length; i++)
res = addTwoBinary(res, arr[i]);
return res;
}
// Driver program
const arr = ["1", "10", "11"];
console.log( addBinary(arr));
Output
110
Time Complexity: O(n * maxLen), where n is the size of the array and maxLen is maximum length of any binary string.
Auxiliary Space: O(maxLen), for result string.