Find a number which give minimum sum when XOR with every number of array of integers | Function to find an integer X such that the sum of all the array elements after getting XORed with X is minimum ; Finding Maximum element of array ; Find Maximum number of bits required in the binary representation of maximum number so log2 is calculated ; Running loop from p times which is the number of bits required to represent all the elements of the array ; If the bits in same position are set then count ; If count becomes greater than half of size of array then we need to make that bit '0' by setting X bit to '1' ; Again using shift operation to calculate the required number ; Calculate minimized sum ; Print solution ; Driver code
function findX ( arr , n ) { let itr = Math . max ( ... arr ) ; let p = parseInt ( Math . log ( itr ) / Math . log ( 2 ) ) + 1 ; let X = 0 ; for ( let i = 0 ; i < p ; i ++ ) { let count = 0 ; for ( let j = 0 ; j < n ; j ++ ) { if ( arr [ j ] & ( 1 << i ) ) { count ++ ; } } if ( count > parseInt ( n / 2 ) ) { X += 1 << i ; } } let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) sum += ( X ^ arr [ i ] ) ; document . write ( " " + X + " " + sum ) ; } let arr = [ 2 , 3 , 4 , 5 , 6 ] ; let n = arr . length ; findX ( arr , n ) ;