# Bitwise OR of N binary strings in C++

In this problem, we are given an array bin[] of size n of binary strings. Our task is to create a program to find the Bitwise OR (&) of n binary strings.

Here, we will take all numbers and find the bitwise AND of them i.e. bin | bin |... bin[n-2] | bin[n]

Let’s take an example to understand the problem,

Input

bin[] = {“1001”, “11001”, “010101”}

Output

011101

Explanation − Bitwise OR of all binary string −

(1001) | (11001) | (010101) = 011101

To solve this problem, We will simply find the string with the largest number of bits (max length string). Then we will add an adequate number of leading 0 to all strings. Then find the Bitwise OR of the bits.

Let’s take an example to show the working of the algorithm −

bin[] = {“1101”, “011010” , “00111”}

Max length string is 011010 with length 6. So, we will add leading 0’s to other strings.

Updated strings − “001101”, “011010”, “000111”.

Finding BITWISE OR of all strings − 001101 | 011010 | 000111 = 011111

## Example

Program to illustrate the working of our solution −

Live Demo

#include <bits/stdc++.h>
using namespace std;
string bitwiseOR(string* bin, int n){
string result;
int max_size = INT_MIN;
for (int i = 0; i < n; i++) {
max_size = max(max_size, (int)bin[i].size());
reverse(bin[i].begin(), bin[i].end());
}
for (int i = 0; i < n; i++) {
string s;
for (int j = 0; j < max_size - bin[i].size(); j++) s += '0';
bin[i] = bin[i] + s;
}
for (int i = 0; i < max_size; i++) {
int insertBit = 0;
for (int j = 0; j < n; j++)
insertBit = insertBit | (bin[j][i] - '0');
result += (insertBit + '0');
}
reverse(result.begin(), result.end());
return result;
}
int main() {
string bin[] = { "1101", "011010", "00111" };
int n = sizeof(bin) / sizeof(bin);
cout<<"The bitwise OR of all the binary String of the string array is "<<bitwiseOR(bin, n);
return 0;
}

## Output

The bitwise OR of all the binary String of the string array is 011111