Bitwise AND of N binary strings
Last Updated :
10 Nov, 2022
Given an array arr[] of binary strings, the task is to calculate the bitwise AND of all of these strings and print the resultant string.
Examples:
Input: arr[] = {"101", "110110", "111"}
Output: 000100
Explanation: (000101) & (110110) & (000111) = 000100
Input: arr[] = {"110010101", "111101001"}
Output: 110000001
Approach 1: Similar to Add two bit strings(https://www.geeksforgeeks.org/add-two-bit-strings/)
Given an array of N binary strings. We first compute the AND operation of the first two binary strings and then perform this "Result" with third binary string and so on till the last binary string.
For Example, string arr[] = {"101", "110110", "111"};
Step 1: Result = 101 AND 110110;
Step 2: Result = Result(Step1) AND 111;
So on..
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Helper method: given two unequal sized
// bit strings, converts them to
// same length by adding leading 0s in the
// smaller string. Returns the new length
int makeEqualLength(string &a, string &b)
{
int len_a = a.length();
int len_b = b.length();
int num_zeros = abs(len_a-len_b);
if (len_a<len_b)
{
for (int i = 0 ; i<num_zeros; i++)
{
a = '0' + a;
}
// Return len_b which is highest.
// No need to proceed further!
return len_b;
}
else
{
for (int i = 0 ; i<num_zeros; i++)
{
b = '0' + b;
}
}
// Return len_a which is greater or
// equal to len_b
return len_a;
}
// The main function that performs AND
// operation of two-bit sequences
// and returns the resultant string
string andOperationBitwise(string s1, string s2)
{
// Make both strings of same length with the
// maximum length of s1 & s2.
int length = makeEqualLength(s1,s2);
// Initialize res as NULL string
string res = "";
// We start from left to right as we have
// made both strings of same length.
for (int i = 0 ; i<length; i++)
{
// Convert s1[i] and s2[i] to int and perform
// bitwise AND operation, append to "res" string
res = res + (char)((s1[i] - '0' & s2[i]-'0')+'0');
}
return res;
}
//Driver Code
int main()
{
string arr[] = {"101", "110110", "111"};
int n = sizeof(arr)/sizeof(arr[0]);
string result;
// Check corner case: If there is just one
// binary string, then print it and return.
if (n<2)
{
cout<<arr[n-1]<<endl;
return 0;
}
result = arr[0];
for (int i = 1; i<n; i++)
{
result = andOperationBitwise(result, arr[i]);
}
cout <<result<<endl;
}
// This code has been contributed by sharathmaidargi
Java
// Java implementation of the above approach
class GFG {
// global fields
static String a;
static String b;
// Helper method: given two unequal sized
// bit strings, converts them to
// same length by adding leading 0s in the
// smaller string. Returns the new length
static int makeEqualLength()
{
int len_a = a.length();
int len_b = b.length();
int num_zeros = Math.abs(len_a - len_b);
if (len_a < len_b) {
for (int i = 0; i < num_zeros; i++) {
a = '0' + a;
}
// Return len_b which is highest.
// No need to proceed further!
return len_b;
}
else {
for (int i = 0; i < num_zeros; i++) {
b = '0' + b;
}
}
// Return len_a which is greater or
// equal to len_b
return len_a;
}
// The main function that performs AND
// operation of two-bit sequences
// and returns the resultant string
static String andOperationBitwise(String s1, String s2)
{
// Make both strings of same length with the
// maximum length of s1 & s2.
a = s1;
b = s2;
int length = makeEqualLength();
s1 = a;
s2 = b;
// Initialize res as NULL string
String res = "";
// We start from left to right as we have
// made both strings of same length.
for (int i = 0; i < length; i++) {
// Convert s1[i] and s2[i] to int and perform
// bitwise AND operation, append to "res" string
res = res
+ (char)((s1.charAt(i) - '0'
& s2.charAt(i) - '0')
+ '0');
}
return res;
}
// Driver code
public static void main(String[] args)
{
String arr[] = { "101", "110110", "111" };
int n = arr.length;
String result = "";
// Check corner case: If there is just one
// binary string, then print it and return.
if (n < 2) {
System.out.println(arr[n - 1]);
}
result = arr[0];
for (int i = 1; i < n; i++) {
result = andOperationBitwise(result, arr[i]);
}
System.out.println(result);
}
}
// This code is contributed by phasing17
Python3
# Python3 implementation of above approach
# this function takes two unequal sized
# bit strings, converts them to
# same length by adding leading 0s in the
# smaller string. Returns the new length
def makeEqualLength(a, b):
len_a = len(a)
len_b = len(b)
num_zeros = abs(len_a - len_b)
if (len_a < len_b):
for i in range(num_zeros):
a = '0' + a
# Return len_b which is highest.
# No need to proceed further!
return len_b, a, b
else:
for i in range(num_zeros):
b = '0' + b
# Return len_a which is greater or
# equal to len_b
return len_a, a, b
# The main function that performs AND
# operation of two-bit sequences
# and returns the resultant string
def andOperationBitwise(s1, s2):
# Make both strings of same length
# with the maximum length of s1 & s2.
length, s1, s2 = makeEqualLength(s1, s2)
# Initialize res as NULL string
res = ""
# We start from left to right as we have
# made both strings of same length.
for i in range(length):
# Convert s1[i] and s2[i] to int
# and perform bitwise AND operation,
# append to "res" string
res = res + str(int(s1[i]) & int(s2[i]))
return res
# Driver Code
arr = ["101", "110110", "111"]
n = len(arr)
if (n < 2):
print(arr[n - 1])
else:
result = arr[0]
for i in range(n):
result = andOperationBitwise(result, arr[i]);
print(result)
# This code is contributed by
# ANKITKUMAR34
C#
// C# implementation of the above approach
using System;
class GFG {
// global fields
static string a;
static string b;
// Helper method: given two unequal sized
// bit strings, converts them to
// same length by adding leading 0s in the
// smaller string. Returns the new length
static int makeEqualLength()
{
int len_a = a.Length;
int len_b = b.Length;
int num_zeros = Math.Abs(len_a - len_b);
if (len_a < len_b) {
for (int i = 0; i < num_zeros; i++) {
a = '0' + a;
}
// Return len_b which is highest.
// No need to proceed further!
return len_b;
}
else {
for (int i = 0; i < num_zeros; i++) {
b = '0' + b;
}
}
// Return len_a which is greater or
// equal to len_b
return len_a;
}
// The main function that performs AND
// operation of two-bit sequences
// and returns the resultant string
static string andOperationBitwise(string s1, string s2)
{
// Make both strings of same length with the
// maximum length of s1 & s2.
a = s1;
b = s2;
int length = makeEqualLength();
s1 = a;
s2 = b;
// Initialize res as NULL string
string res = "";
// We start from left to right as we have
// made both strings of same length.
for (int i = 0; i < length; i++) {
// Convert s1[i] and s2[i] to int and perform
// bitwise AND operation, append to "res" string
res = res
+ (char)((s1[i] - '0' & s2[i] - '0')
+ '0');
}
return res;
}
// Driver code
public static void Main(string[] args)
{
string[] arr = { "101", "110110", "111" };
int n = arr.Length;
string result = "";
// Check corner case: If there is just one
// binary string, then print it and return.
if (n < 2) {
Console.WriteLine(arr[n - 1]);
}
result = arr[0];
for (int i = 1; i < n; i++) {
result = andOperationBitwise(result, arr[i]);
}
Console.WriteLine(result);
}
}
// This code is contributed by phasing17
JavaScript
<script>
// Javascript implementation of the above approach
// Helper method: given two unequal sized
// bit strings, converts them to
// same length by adding leading 0s in the
// smaller string. Returns the new length
let s1, s2;
function makeEqualLength()
{
let len_a = s1.length;
let len_b = s2.length;
let num_zeros = Math.abs(len_a - len_b);
if (len_a < len_b)
{
for(let i = 0; i < num_zeros; i++)
{
s1 = '0' + s1;
}
// Return len_b which is highest.
// No need to proceed further!
return len_b;
}
else
{
for(let i = 0; i < num_zeros; i++)
{
s2 = '0' + s2;
}
}
// Return len_a which is greater or
// equal to len_b
return len_a;
}
// The main function that performs AND
// operation of two-bit sequences
// and returns the resultant string
function andOperationBitwise()
{
// Make both strings of same length with the
// maximum length of s1 & s2.
let length = makeEqualLength();
// Initialize res as NULL string
let res = "";
// We start from left to right as we have
// made both strings of same length.
for(let i = 0 ; i<length; i++)
{
// Convert s1[i] and s2[i] to int
// and perform bitwise AND operation,
// append to "res" string
res = res + String.fromCharCode((s1[i].charCodeAt() -
'0'.charCodeAt() &
s2[i].charCodeAt() -
'0'.charCodeAt()) +
'0'.charCodeAt());
}
return res;
}
// Driver code
let arr = [ "101", "110110", "111" ];
let n = arr.length;
let result;
// Check corner case: If there is just one
// binary string, then print it and return.
if (n < 2)
{
document.write(arr[n - 1] + "</br>");
}
result = arr[0];
for(let i = 1; i<n; i++)
{
s1 = result;
s2 = arr[i];
result = andOperationBitwise();
}
document.write(result);
// This code is contributed by vaibhavrabadiya3
</script>
Time Complexity: O(n *(length)), where n is the number of binary strings, and length is the length of the longest binary string.
Auxiliary Space: O(length), where length is the length of the longest binary string.
Approach 2: Find the size of the smallest and the largest string. We need this to add (largest-smallest) zeroes to our result. For example, if we have 0010 and 11, then AND on these strings will be 0010 (since we can write 11 as 0011). Then perform AND operation on each bit.
We can achieve this by only finding if the current bit in any string is 0 or not. If current bit is 0 in any of the given strings, then AND operation on that bit will be 0. If all bits at the current position are 1, then AND operation will be 1.
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the bitwise AND of
// all the binary strings
string strBitwiseAND(string* arr, int n)
{
string res;
// To store the largest and the smallest
// string's size, We need this to add '0's
// in the resultant string
int smallest_size = INT_MAX;
int largest_size = INT_MIN;
// Reverse each string
// Since we need to perform AND operation
// on bits from Right to Left
for (int i = 0; i < n; i++) {
reverse(arr[i].begin(), arr[i].end());
// Update the respective length values
smallest_size = min(smallest_size, (int)arr[i].size());
largest_size = max(largest_size, (int)arr[i].size());
}
// Traverse bits from 0 to smallest string's size
for (int i = 0; i < smallest_size; i++) {
bool all_ones = true;
for (int j = 0; j < n; j++) {
// If at this bit position, there is a 0
// in any of the given strings then AND
// operation on current bit position
// will be 0
if (arr[j][i] == '0') {
all_ones = false;
break;
}
}
// Add resultant bit to result
res += (all_ones ? '1' : '0');
}
// Add 0's to the string.
for (int i = 0; i < largest_size - smallest_size; i++)
res += '0';
// Reverse the string
// Since we started from LEFT to RIGHT
reverse(res.begin(), res.end());
// Return the resultant string
return res;
}
// Driver code
int main()
{
string arr[] = { "101", "110110", "111" };
int n = sizeof(arr) / sizeof(arr[0]);
cout << strBitwiseAND(arr, n);
return 0;
}
Java
// Java implementation of the above approach
class GfG
{
// Function to find the bitwise AND of
// all the binary strings
static String strBitwiseAND(String[] arr, int n)
{
String res = "";
// To store the largest and the smallest
// string's size, We need this to add
// '0's in the resultant string
int smallest_size = Integer.MAX_VALUE;
int largest_size = Integer.MIN_VALUE;
// Reverse each string
// Since we need to perform AND operation
// on bits from Right to Left
for (int i = 0; i < n; i++)
{
StringBuilder temp = new StringBuilder();
temp.append(arr[i]);
arr[i] = temp.reverse().toString();
// Update the respective length values
smallest_size = Math.min(smallest_size, arr[i].length());
largest_size = Math.max(largest_size, arr[i].length());
}
// Traverse bits from 0 to smallest string's size
for (int i = 0; i < smallest_size; i++)
{
boolean all_ones = true;
for (int j = 0; j < n; j++)
{
// If at this bit position, there is a 0
// in any of the given strings then AND
// operation on current bit position
// will be 0
if (arr[j].charAt(i) == '0')
{
all_ones = false;
break;
}
}
// Add resultant bit to result
res += (all_ones ? '1' : '0');
}
// Add 0's to the string.
for (int i = 0; i < largest_size - smallest_size; i++)
res += '0';
// Reverse the string
// Since we started from LEFT to RIGHT
StringBuilder temp = new StringBuilder();
temp.append(res);
res = temp.reverse().toString();
// Return the resultant string
return res;
}
// Driver code
public static void main(String []args)
{
String arr[] = { "101", "110110", "111" };
int n = arr.length;
System.out.println(strBitwiseAND(arr, n));
}
}
// This code is contributed by Rituraj Jain
Python3
# Python3 implementation of the above approach
import sys;
# Function to find the bitwise AND of
# all the binary strings
def strBitwiseAND(arr, n) :
res = ""
# To store the largest and the smallest
# string's size, We need this to add '0's
# in the resultant string
smallest_size = sys.maxsize;
largest_size = -(sys.maxsize - 1);
# Reverse each string
# Since we need to perform AND operation
# on bits from Right to Left
for i in range(n) :
arr[i] = arr[i][::-1] ;
# Update the respective length values
smallest_size = min(smallest_size, len(arr[i]));
largest_size = max(largest_size, len(arr[i]));
# Traverse bits from 0 to smallest string's size
for i in range(smallest_size) :
all_ones = True;
for j in range(n) :
# If at this bit position, there is a 0
# in any of the given strings then AND
# operation on current bit position
# will be 0
if (arr[j][i] == '0') :
all_ones = False;
break;
# Add resultant bit to result
if all_ones :
res += '1' ;
else :
res += '0' ;
# Add 0's to the string.
for i in range(largest_size - smallest_size) :
res += '0';
# Reverse the string
# Since we started from LEFT to RIGHT
res = res[::-1];
# Return the resultant string
return res;
# Driver code
if __name__ == "__main__" :
arr = [ "101", "110110", "111" ];
n = len(arr) ;
print(strBitwiseAND(arr, n));
# This code is contributed by Ryuga
C#
// C# implementation of the above approach:
using System;
class GfG
{
// Function to find the bitwise AND of
// all the binary strings
static String strBitwiseAND(String[] arr, int n)
{
String res = "";
// To store the largest and the smallest
// string's size, We need this to add
// '0's in the resultant string
int smallest_size = int.MaxValue;
int largest_size = int.MinValue;
// Reverse each string
// Since we need to perform AND operation
// on bits from Right to Left
String temp ="";
for (int i = 0; i < n; i++)
{
temp+=arr[i];
arr[i] = reverse(temp);
// Update the respective length values
smallest_size = Math.Min(smallest_size, arr[i].Length);
largest_size = Math.Max(largest_size, arr[i].Length);
}
// Traverse bits from 0 to smallest string's size
for (int i = 0; i < smallest_size; i++)
{
bool all_ones = true;
for (int j = 0; j < n; j++)
{
// If at this bit position, there is a 0
// in any of the given strings then AND
// operation on current bit position
// will be 0
if (arr[j][i] == '0')
{
all_ones = false;
break;
}
}
// Add resultant bit to result
res += (all_ones ? '1' : '0');
}
// Add 0's to the string.
for (int i = 0; i < largest_size - smallest_size; i++)
res += '0';
// Reverse the string
// Since we started from LEFT to RIGHT
String temp1 = "";
temp1+=res;
res = reverse(temp1);
// Return the resultant string
return res;
}
static String reverse(String input)
{
char[] temparray = input.ToCharArray();
int left, right = 0;
right = temparray.Length - 1;
for (left = 0; left < right; left++, right--)
{
// Swap values of left and right
char temp = temparray[left];
temparray[left] = temparray[right];
temparray[right] = temp;
}
return String.Join("",temparray);
}
// Driver code
public static void Main(String []args)
{
String []arr = { "101", "110110", "111" };
int n = arr.Length;
Console.WriteLine(strBitwiseAND(arr, n));
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// JavaScript implementation of the above approach:
// Function to find the bitwise AND of
// all the binary strings
function strBitwiseAND(arr, n)
{
let res = "";
// To store the largest and the smallest
// string's size, We need this to add
// '0's in the resultant string
let smallest_size = Number.MAX_VALUE;
let largest_size = Number.MIN_VALUE;
// Reverse each string
// Since we need to perform AND operation
// on bits from Right to Left
let temp ="";
for (let i = 0; i < n; i++)
{
temp+=arr[i];
arr[i] = reverse(temp);
// Update the respective length values
smallest_size = Math.min(smallest_size, arr[i].length);
largest_size = Math.max(largest_size, arr[i].length);
}
// Traverse bits from 0 to smallest string's size
for (let i = 0; i < smallest_size; i++)
{
let all_ones = true;
for (let j = 0; j < n; j++)
{
// If at this bit position, there is a 0
// in any of the given strings then AND
// operation on current bit position
// will be 0
if (arr[j][i] == '0')
{
all_ones = false;
break;
}
}
// Add resultant bit to result
res += (all_ones ? '1' : '0');
}
// Add 0's to the string.
for (let i = 0; i < largest_size - smallest_size; i++)
res += '0';
// Reverse the string
// Since we started from LEFT to RIGHT
let temp1 = "";
temp1+=res;
res = reverse(temp1);
// Return the resultant string
let temparray1 = res;
let Temparray = "";
for(let i = 6; i < temparray1.length; i++)
{
Temparray = Temparray + temparray1[i];
}
return Temparray;
}
function reverse(input)
{
let temparray = input.split('');
let left, right = 0;
right = temparray.length - 1;
for (left = 0; left < right; left++, right--)
{
// Swap values of left and right
let temp = temparray[left];
temparray[left] = temparray[right];
temparray[right] = temp;
}
return temparray.join("");
}
let arr = [ "101", "110110", "111" ];
let n = arr.length;
document.write(strBitwiseAND(arr, n));
</script>
Time Complexity: O(max(n, length)), where n is the number of binary strings, and length is the length of the longest binary string
Auxiliary Space: O(length), where length is the length of the longest binary string
Similar Reads
Bitwise OR of N binary strings
Given an array arr[] of binary strings, the task is to calculate the bitwise OR of all of these strings and print the resultant string.Examples: Input: arr[] = {"100", "1001", "0011"} Output 1111 0100 OR 1001 OR 0011 = 1111Input: arr[] = {"10", "11", "1000001"} Output: 1000011 Approach: We can do th
7 min read
Generate all the binary strings of N bits
Given a positive integer number N. The task is to generate all the binary strings of N bits. These binary strings should be in ascending order.Examples: Input: 2Output:0 00 11 01 1Input: 3Output:0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1Approach: The idea is to try every permutation. For every positio
8 min read
Bitwise XOR of a Binary array
Given a binary array arr[], the task is to calculate the bitwise XOR of all the elements in this array and print it. Examples: Input: arr[] = {â100â, â1001â, â0011â} Output: 1110 0100 XOR 1001 XOR 0011 = 1110 Input: arr[] = {â10â, â11â, â1000001â} Output: 1000000 Approach: Step 1: First find the max
7 min read
Print bitwise AND set of a number N
Given a number N, print all the numbers which are a bitwise AND set of the binary representation of N. Bitwise AND set of a number N is all possible numbers x smaller than or equal N such that N & i is equal to x for some number i. Examples : Input : N = 5Output : 0, 1, 4, 5 Explanation: 0 &
8 min read
Add two binary strings
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:Input: s1 = "00100", s2 = "010" Output: "110" Bit-by-bit additio
8 min read
Check for Binary String
Given a string s, the task is to check if it is a binary string or not. A binary string is a string which only contains the characters '0' and '1'.Examples:Input: s = "01010101010"Output: trueInput: s = "geeks101"Output: false Approach:The idea is to iterate over all the characters of the string and
3 min read
Count of 1-bit and 2-bit characters in the given binary string
Given two special characters, the first character can be represented by one bit which is 0 and the second character can be represented by two bits either 10 or 11. Now given a string represented by several bits. The task is to return the number of characters it represents. Note that the given string
4 min read
Bitwise AND of all the elements of array
Given an array, arr[] of N integers, the task is to find out the bitwise AND(&) of all the elements of the array. Examples: Input: arr[] = {1, 3, 5, 9, 11} Output: 1 Input: arr[] = {3, 7, 11, 19, 11} Output: 3 Approach: The idea is to traverse all the array elements and compute the bitwise AND f
4 min read
What is Binary String?
A binary string is a string that only has two characters, usually the numbers 0 and 1, and it represents a series of binary digits. Binary String Variables:In computer programming, binary string variables are used to store binary data, which is data that is represented in a binary (base-2) format, r
9 min read
Count of all possible N length balanced Binary Strings
Given a number N, the task is to find the total number of balanced binary strings possible of length N. A binary string is said to be balanced if: The number of 0s and 1s are equal in each binary stringThe count of 0s in any prefix of binary strings is always greater than or equal to the count of 1s
6 min read