Minimum flips required to maximize a number with k set bits | CPP for finding min flip for maximizing given n ; function for finding set bit ; return count of set bit ; function for finding min flip ; number of bits in n ; Find the largest number of same size with k set bits ; Count bit differences to find required flipping . ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int setBit ( int xorValue ) { int count = 0 ; while ( xorValue ) { if ( xorValue % 2 ) count ++ ; xorValue /= 2 ; } return count ; } int minFlip ( int n , int k ) { int size = log2 ( n ) + 1 ; int max = pow ( 2 , k ) - 1 ; max = max << ( size - k ) ; int xorValue = ( n ^ max ) ; return ( setBit ( xorValue ) ) ; } int main ( ) { int n = 27 , k = 3 ; cout << " Min ▁ Flips ▁ = ▁ " << minFlip ( n , k ) ; return 0 ; }