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 Code
< ? php function setBit ( $ xorValue ) { $ count = 0 ; while ( $ xorValue ) { if ( $ xorValue % 2 ) $ count ++ ; $ xorValue /= 2 ; } return $ count ; } function minFlip ( $ n , $ k ) { $ size = log ( $ n ) + 1 ; $ max = pow ( 2 , $ k ) - 1 ; $ max = $ max << ( $ size - $ k ) ; $ xorValue = ( $ n ^ $ max ) ; return ( setBit ( $ xorValue ) ) ; } $ n = 27 ; $ k = 3 ; echo " Min ▁ Flips ▁ = ▁ " , minFlip ( $ n , $ k ) ; ? >