human
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"
How can the above be solved in Python?
assistant
#Here is code to largest number less than X having at most K set bits and the other steps required.
 def greatestKBits ( X , K ) :
	set_bit_count = bin ( X ) . count ( '1' )
	if ( set_bit_count <= K ) :
		return X
	diff = set_bit_count - K
	for i in range ( 0 , diff , 1 ) :
		X &= ( X - 1 )
	return X
if __name__ == ' _ _ main _ _ ' :
	X = 21
	K = 2
	print ( greatestKBits ( X , K ) )