Sum of Bitwise XOR of elements of an array with all elements of another array | C ++ Program for the above approach ; Function to calculate sum of Bitwise XOR of elements of arr [ ] with k ; Initialize sum to be zero ; Iterate over each set bit ; Stores contribution of i - th bet to the sum ; If the i - th bit is set ; Stores count of elements whose i - th bit is not set ; Update value ; Update value ; Add value to sum ; Move to the next power of two ; Stores the count of elements whose i - th bit is set ; Initialize count to 0 for all positions ; Traverse the array ; Iterate over each bit ; If the i - th bit is set ; Increase count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorSumOfArray ( int arr [ ] , int n , int k , int count [ ] ) { int sum = 0 ; int p = 1 ; for ( int i = 0 ; i < 31 ; i ++ ) { int val = 0 ; if ( ( k & ( 1 << i ) ) != 0 ) { int not_set = n - count [ i ] ; val = ( ( not_set ) * p ) ; } else { val = ( count [ i ] * p ) ; } sum += val ; p = ( p * 2 ) ; } return sum ; } void sumOfXors ( int arr [ ] , int n , int queries [ ] , int q ) { int count [ 32 ] ; memset ( count , 0 , sizeof ( count ) ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 31 ; j ++ ) { if ( arr [ i ] & ( 1 << j ) ) count [ j ] ++ ; } } for ( int i = 0 ; i < q ; i ++ ) { int k = queries [ i ] ; cout << xorSumOfArray ( arr , n , k , count ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 5 , 2 , 3 } ; int queries [ ] = { 3 , 8 , 7 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int q = sizeof ( queries ) / sizeof ( int ) ; sumOfXors ( arr , n , queries , q ) ; return 0 ; }