Sum of Bitwise AND of each array element with the elements of another array | Java program for the above approach ; Driver Code ; Given arr1 [ ] ; Given arr2 [ ] ; Size of arr1 [ ] ; Size of arr2 [ ] ; Function Call ; 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 the sum obtained for ith number in arr1 [ ]
import java . io . * ; class GFG { public static void main ( String [ ] args ) { int [ ] arr1 = { 1 , 2 , 3 } ; int [ ] arr2 = { 1 , 2 , 3 } ; int N = arr1 . length ; int M = arr2 . length ; Bitwise_AND_sum_i ( arr1 , arr2 , M , N ) ; } static void Bitwise_AND_sum_i ( int arr1 [ ] , int arr2 [ ] , int M , int N ) { int [ ] frequency = new int [ 32 ] ; for ( int i = 0 ; i < N ; i ++ ) { int bit_position = 0 ; int num = arr1 [ i ] ; while ( num != 0 ) { if ( ( num & 1 ) != 0 ) { frequency [ bit_position ] += 1 ; } bit_position += 1 ; num >>= 1 ; } } for ( int i = 0 ; i < M ; i ++ ) { int num = arr2 [ i ] ; int value_at_that_bit = 1 ; int bitwise_AND_sum = 0 ; for ( int bit_position = 0 ; bit_position < 32 ; bit_position ++ ) { if ( ( num & 1 ) != 0 ) { bitwise_AND_sum += frequency [ bit_position ] * value_at_that_bit ; } num >>= 1 ; value_at_that_bit <<= 1 ; } System . out . print ( bitwise_AND_sum + " ▁ " ) ; } } }