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
using System ; public class GFG { static 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 ; } static void sumOfXors ( int [ ] arr , int n , int [ ] queries , int q ) { int [ ] count = new int [ 32 ] ; for ( int i = 0 ; i < 32 ; i ++ ) count [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 31 ; j ++ ) { if ( ( arr [ i ] & ( 1 << j ) ) != 0 ) count [ j ] ++ ; } } for ( int i = 0 ; i < q ; i ++ ) { int k = queries [ i ] ; Console . Write ( xorSumOfArray ( arr , n , k , count ) + " ▁ " ) ; } } static public void Main ( ) { int [ ] arr = { 5 , 2 , 3 } ; int [ ] queries = { 3 , 8 , 7 } ; int n = arr . Length ; int q = queries . Length ; sumOfXors ( arr , n , queries , q ) ; } }