Minimum flips required to maximize a number with k set bits | Python3 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 Code
import math NEW_LINE def setBit ( xorValue ) : NEW_LINE INDENT count = 0 NEW_LINE while ( xorValue ) : NEW_LINE INDENT if ( xorValue % 2 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT xorValue = int ( xorValue / 2 ) NEW_LINE DEDENT return count NEW_LINE DEDENT def minFlip ( n , k ) : NEW_LINE INDENT size = int ( math . log ( n ) / math . log ( 2 ) + 1 ) NEW_LINE max = pow ( 2 , k ) - 1 NEW_LINE max = max << ( size - k ) NEW_LINE xorValue = ( n ^ max ) NEW_LINE return ( setBit ( xorValue ) ) NEW_LINE DEDENT n = 27 NEW_LINE k = 3 NEW_LINE print ( " Min ▁ Flips ▁ = ▁ " , minFlip ( n , k ) ) NEW_LINE