Find a number which give minimum sum when XOR with every number of array of integers | Java implementation of above approach ; 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
import java . lang . Math ; import java . util . * ; class GFG { public static void findX ( int [ ] a , int n ) { Collections . sort ( Arrays . asList ( a ) , null ) ; int itr = a [ n - 1 ] ; int p = ( int ) ( Math . log ( itr ) / Math . log ( 2 ) ) + 1 ; int x = 0 ; for ( int i = 0 ; i < p ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( a [ j ] & ( 1 << i ) ) != 0 ) count ++ ; } if ( count > ( n / 2 ) ) { x += 1 << i ; } } long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += ( x ^ a [ i ] ) ; System . out . println ( " X ▁ = ▁ " + x + " , ▁ Sum ▁ = ▁ " + sum ) ; } public static void main ( String [ ] args ) { int [ ] a = { 2 , 3 , 4 , 5 , 6 } ; int n = a . length ; findX ( a , n ) ; } }