Sum of Bitwise XOR of each array element with all other array elements | C ++ program for the above approach ; Function to calculate for each array element , sum of its Bitwise XOR with all other array elements ; Declare an array of size 64 to store count of each bit ; Traversing the array ; Check if bit is present of not ; Increase the bit position ; Reduce the number to half ; Traverse the array ; Stores the bit position ; Stores the sum of Bitwise XOR ; Check if bit is present of not ; Reduce the number to its half ; Print the sum for A [ i ] ; Driver Code ; Given array ; Given N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void XOR_for_every_i ( int A [ ] , int N ) { int frequency_of_bits [ 32 ] { } ; for ( int i = 0 ; i < N ; i ++ ) { int bit_position = 0 ; int M = A [ i ] ; while ( M ) { if ( M & 1 ) { frequency_of_bits [ bit_position ] += 1 ; } bit_position += 1 ; M >>= 1 ; } } for ( int i = 0 ; i < N ; i ++ ) { int M = A [ i ] ; int value_at_that_bit = 1 ; int XOR_sum = 0 ; for ( int bit_position = 0 ; bit_position < 32 ; bit_position ++ ) { if ( M & 1 ) { XOR_sum += ( N - frequency_of_bits [ bit_position ] ) * value_at_that_bit ; } else { XOR_sum += ( frequency_of_bits [ bit_position ] ) * value_at_that_bit ; } M >>= 1 ; value_at_that_bit <<= 1 ; } cout << XOR_sum << ' ▁ ' ; } return ; } int main ( ) { int A [ ] = { 1 , 2 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; XOR_for_every_i ( A , N ) ; return 0 ; }