Bitwise AND of N binary strings | C ++ implementation of the above approach ; Helper method : given two unequal sized bit strings , converts them to same length by adding leading 0 s in the smaller string . Returns the the new length ; Return len_b which is highest . No need to proceed further ! ; Return len_a which is greater or equal to len_b ; The main function that performs AND operation of two - bit sequences and returns the resultant string ; Make both strings of same length with the maximum length of s1 & s2 . ; Initialize res as NULL string ; We start from left to right as we have made both strings of same length . ; Convert s1 [ i ] and s2 [ i ] to int and perform bitwise AND operation , append to " res " string ; Driver Code ; Check corner case : If there is just one binary string , then print it and return .
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; } else { for ( int i = 0 ; i < num_zeros ; i ++ ) { b = '0' + b ; } } return len_a ; } string andOperationBitwise ( string s1 , string s2 ) { int length = makeEqualLength ( s1 , s2 ) ; string res = " " ; for ( int i = 0 ; i < length ; i ++ ) { res = res + ( char ) ( ( s1 [ i ] - '0' & s2 [ i ] - '0' ) + '0' ) ; } return res ; } int main ( ) { string arr [ ] = { "101" , "110110" , "111" } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string result ; 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 ; }