Minimizing array sum by applying XOR operation on all elements of the array | C ++ implementation of the approach ; Function to return the minimized sum ; To store the frequency of bit in every element ; Finding element X ; Taking XOR of elements and finding sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 25 ; int getMinSum ( int arr [ ] , int n ) { int bits_count [ MAX ] , max_bit = 0 , sum = 0 , ans = 0 ; memset ( bits_count , 0 , sizeof ( bits_count ) ) ; for ( int d = 0 ; d < n ; d ++ ) { int e = arr [ d ] , f = 0 ; while ( e > 0 ) { int rem = e % 2 ; e = e / 2 ; if ( rem == 1 ) { bits_count [ f ] += rem ; } f ++ ; } max_bit = max ( max_bit , f ) ; } for ( int d = 0 ; d < max_bit ; d ++ ) { int temp = pow ( 2 , d ) ; if ( bits_count [ d ] > n / 2 ) ans = ans + temp ; } for ( int d = 0 ; d < n ; d ++ ) { arr [ d ] = arr [ d ] ^ ans ; sum = sum + arr [ d ] ; } return sum ; } int main ( ) { int arr [ ] = { 3 , 5 , 7 , 11 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMinSum ( arr , n ) ; return 0 ; }