Minimum number of bits of array elements required to be flipped to make all array elements equal | C ++ program for the above approach ; Function to count minimum number of bits required to be flipped to make all array elements equal ; Stores the count of unset bits ; Stores the count of set bits ; Traverse the array ; Traverse the bit of arr [ i ] ; If current bit is set ; Increment fre1 [ j ] ; Otherwise ; Increment fre0 [ j ] ; Right shift x by 1 ; Stores the count of total moves ; Traverse the range [ 0 , 32 ] ; Update the value of ans ; Return the minimum number of flips required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int makeEqual ( int * arr , int n ) { int fre0 [ 33 ] = { 0 } ; int fre1 [ 33 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int x = arr [ i ] ; for ( int j = 0 ; j < 33 ; j ++ ) { if ( x & 1 ) { fre1 [ j ] += 1 ; } else { fre0 [ j ] += 1 ; } x = x >> 1 ; } } int ans = 0 ; for ( int i = 0 ; i < 33 ; i ++ ) { ans += min ( fre0 [ i ] , fre1 [ i ] ) ; } return ans ; } int main ( ) { int arr [ ] = { 3 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << makeEqual ( arr , N ) ; return 0 ; }