Minimum flips required to maximize a number with k set bits | JAVA Code to find Minimum flips required to maximize a number with k set bits ; 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 to test above function
import java . util . * ; class GFG { static int setBit ( int xorValue ) { int count = 0 ; while ( xorValue >= 1 ) { if ( xorValue % 2 == 1 ) count ++ ; xorValue /= 2 ; } return count ; } static int minFlip ( int n , int k ) { int size = ( int ) ( Math . log ( n ) / Math . log ( 2 ) ) + 1 ; int max = ( int ) Math . pow ( 2 , k ) - 1 ; max = max << ( size - k ) ; int xorValue = ( n ^ max ) ; return ( setBit ( xorValue ) ) ; } public static void main ( String [ ] args ) { int n = 27 , k = 3 ; System . out . println ( " Min ▁ Flips ▁ = ▁ " + minFlip ( n , k ) ) ; } }