Sum of Bitwise AND of each array element with the elements of another array | Function to compute the AND sum for each element of an array ; Declaring an array of size 32 for storing the count of each bit ; Traverse the array arr2 [ ] and store the count of a bit in frequency array ; Current bit position ; While num is greater than 0 ; Checks if ith bit is set or not ; Increment the count of bit by one ; Increment the bit position by one ; Right shift the num by one ; Traverse in the arr2 [ ] ; Store the ith bit value ; Total required sum ; Traverse in the range [ 0 , 31 ] ; Checks if current bit is set ; Increment the bitwise sum by frequency [ bit_position ] * value_at_that_bit ; Right shift num by one ; Left shift vale_at_that_bit by one ; Print sum obtained for ith number in arr1 [ ] ; Driver Code ; Given arr1 [ ] ; Given arr2 ; Size of arr1 [ ] ; Size of arr2 [ ] ; Function Call
def Bitwise_AND_sum_i ( arr1 , arr2 , M , N ) : NEW_LINE INDENT frequency = [ 0 ] * 32 NEW_LINE for i in range ( N ) : NEW_LINE INDENT bit_position = 0 NEW_LINE num = arr1 [ i ] NEW_LINE while ( num ) : NEW_LINE INDENT if ( num & 1 ) : NEW_LINE INDENT frequency [ bit_position ] += 1 NEW_LINE DEDENT bit_position += 1 NEW_LINE num >>= 1 NEW_LINE DEDENT DEDENT for i in range ( M ) : NEW_LINE INDENT num = arr2 [ i ] NEW_LINE value_at_that_bit = 1 NEW_LINE bitwise_AND_sum = 0 NEW_LINE for bit_position in range ( 32 ) : NEW_LINE INDENT if ( num & 1 ) : NEW_LINE INDENT bitwise_AND_sum += frequency [ bit_position ] * value_at_that_bit NEW_LINE DEDENT num >>= 1 NEW_LINE value_at_that_bit <<= 1 NEW_LINE DEDENT print ( bitwise_AND_sum , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 1 , 2 , 3 ] NEW_LINE arr2 = [ 1 , 2 , 3 ] NEW_LINE N = len ( arr1 ) NEW_LINE M = len ( arr2 ) NEW_LINE Bitwise_AND_sum_i ( arr1 , arr2 , M , N ) NEW_LINE DEDENT