Bitwise AND of N binary strings | Java implementation of the above approach ; Function to find the bitwise AND of all the binary strings ; To store the largest and the smallest string ' s ▁ size , ▁ We ▁ need ▁ this ▁ to ▁ add ▁ ▁ ' 0 's in the resultant string ; Reverse each string Since we need to perform AND operation on bits from Right to Left ; Update the respective length values ; Traverse bits from 0 to smallest string 's size ; 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 ; Add resultant bit to result ; Add 0 's to the string. ; Reverse the string Since we started from LEFT to RIGHT ; Return the resultant string ; Driver code
class GfG { static String strBitwiseAND ( String [ ] arr , int n ) { String res = " " ; int smallest_size = Integer . MAX_VALUE ; int largest_size = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { StringBuilder temp = new StringBuilder ( ) ; temp . append ( arr [ i ] ) ; arr [ i ] = temp . reverse ( ) . toString ( ) ; smallest_size = Math . min ( smallest_size , arr [ i ] . length ( ) ) ; largest_size = Math . max ( largest_size , arr [ i ] . length ( ) ) ; } for ( int i = 0 ; i < smallest_size ; i ++ ) { boolean all_ones = true ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] . charAt ( i ) == '0' ) { all_ones = false ; break ; } } res += ( all_ones ? '1' : '0' ) ; } for ( int i = 0 ; i < largest_size - smallest_size ; i ++ ) res += '0' ; StringBuilder temp = new StringBuilder ( ) ; temp . append ( res ) ; res = temp . reverse ( ) . toString ( ) ; return res ; } public static void main ( String [ ] args ) { String arr [ ] = { "101" , "110110" , "111" } ; int n = arr . length ; System . out . println ( strBitwiseAND ( arr , n ) ) ; } }