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 ; Traverse the array ; Iterate over each bit ; If the i - th bit is set ; Increase count ; Driver Code
def xorSumOfArray ( arr , n , k , count ) : NEW_LINE INDENT sum = 0 NEW_LINE p = 1 NEW_LINE for i in range ( 31 ) : NEW_LINE INDENT val = 0 NEW_LINE if ( ( k & ( 1 << i ) ) != 0 ) : NEW_LINE INDENT not_set = n - count [ i ] NEW_LINE val = ( ( not_set ) * p ) NEW_LINE DEDENT else : NEW_LINE INDENT val = ( count [ i ] * p ) NEW_LINE DEDENT sum += val NEW_LINE p = ( p * 2 ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def sumOfXors ( arr , n , queries , q ) : NEW_LINE INDENT count = [ 0 for i in range ( 32 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 31 ) : NEW_LINE INDENT if ( arr [ i ] & ( 1 << j ) ) : NEW_LINE INDENT count [ j ] += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( q ) : NEW_LINE INDENT k = queries [ i ] NEW_LINE print ( xorSumOfArray ( arr , n , k , count ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 2 , 3 ] NEW_LINE queries = [ 3 , 8 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE q = len ( queries ) NEW_LINE sumOfXors ( arr , n , queries , q ) NEW_LINE DEDENT