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
function setBit ( xorValue ) { var count = 0 ; while ( xorValue ) { if ( xorValue % 2 ) count ++ ; xorValue = parseInt ( xorValue / 2 ) ; } return count ; } function minFlip ( n , k ) { var size = Math . log2 ( n ) + 1 ; var max = Math . pow ( 2 , k ) - 1 ; max = ( max << ( size - k ) ) ; var xorValue = ( n ^ max ) ; return ( setBit ( xorValue ) ) ; } var n = 27 , k = 3 ; document . write ( " " + minFlip ( n , k ) ) ;