Largest number less than X having at most K set bits | Function to return the greatest number <= X having at most K set bits . ; Remove rightmost set bits one by one until we count becomes k ; Return the required number ; Driver code
def greatestKBits ( X , K ) : NEW_LINE INDENT set_bit_count = bin ( X ) . count ( '1' ) NEW_LINE if ( set_bit_count <= K ) : NEW_LINE INDENT return X NEW_LINE DEDENT diff = set_bit_count - K NEW_LINE for i in range ( 0 , diff , 1 ) : NEW_LINE INDENT X &= ( X - 1 ) NEW_LINE DEDENT return X NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 21 NEW_LINE K = 2 NEW_LINE print ( greatestKBits ( X , K ) ) NEW_LINE DEDENT