Sum of Bitwise OR of each array element of an array with all elements of another array | C ++ program for the above approach ; Function to compute sum of Bitwise OR of each element in arr1 [ ] with all elements of the array arr2 [ ] ; Declaring an array of size 32 to store the count of each bit ; Traverse the array arr1 [ ] ; Current bit position ; While num exceeds 0 ; Checks if i - th bit is set or not ; Increment the count at bit_position by one ; Increment bit_position ; Right shift the num by one ; Traverse in the arr2 [ ] ; Store the ith bit value ; Total required sum ; Traverse in the range [ 0 , 31 ] ; Check if current bit is set ; Increment the Bitwise sum by N * ( 2 ^ i ) ; Right shift num by one ; Left shift valee_at_that_bit by one ; Print the sum obtained for ith number in arr1 [ ] ; Driver Code ; Given arr1 [ ] ; Given arr2 [ ] ; Size of arr1 [ ] ; Size of arr2 [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Bitwise_OR_sum_i ( int arr1 [ ] , int arr2 [ ] , int M , int N ) { int frequency [ 32 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int bit_position = 0 ; int num = arr1 [ i ] ; while ( num ) { if ( num & 1 ) { 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_OR_sum = 0 ; for ( int bit_position = 0 ; bit_position < 32 ; bit_position ++ ) { if ( num & 1 ) { bitwise_OR_sum += N * value_at_that_bit ; } else { bitwise_OR_sum += frequency [ bit_position ] * value_at_that_bit ; } num >>= 1 ; value_at_that_bit <<= 1 ; } cout << bitwise_OR_sum << ' ▁ ' ; } return ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 3 } ; int arr2 [ ] = { 1 , 2 , 3 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int M = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; Bitwise_OR_sum_i ( arr1 , arr2 , M , N ) ; return 0 ; }