Sum of Bitwise XOR of elements of an array with all elements of another array | 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
function xorSumOfArray ( arr , n , k , count ) { var sum = 0 ; var p = 1 ; for ( var i = 0 ; i < 31 ; i ++ ) { var val = 0 ; if ( ( k & ( 1 << i ) ) != 0 ) { var not_set = n - count [ i ] ; val = ( ( not_set ) * p ) ; } else { val = ( count [ i ] * p ) ; } sum += val ; p = ( p * 2 ) ; } return sum ; } function sumOfXors ( arr , n , queries , q ) { var count = new Array ( 32 ) ; count . fill ( 0 ) ; for ( var i = 0 ; i < n ; i ++ ) { for ( var j = 0 ; j < 31 ; j ++ ) { if ( arr [ i ] & ( 1 << j ) ) count [ j ] ++ ; } } for ( var i = 0 ; i < q ; i ++ ) { var k = queries [ i ] ; document . write ( xorSumOfArray ( arr , n , k , count ) + " " ) ; } } var arr = [ 5 , 2 , 3 ] ; var queries = [ 3 , 8 , 7 ] ; var n = arr . length ; var q = queries . length ; sumOfXors ( arr , n , queries , q ) ;