Largest number less than X having at most K set bits | Java implementation of the approach ; 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
import java . io . * ; class GFG { int greatestKBits ( int X , int K ) { int set_bit_count = Integer . bitCount ( X ) ; if ( set_bit_count <= K ) return X ; int diff = set_bit_count - K ; for ( int i = 0 ; i < diff ; i ++ ) X &= ( X - 1 ) ; return X ; } public static void main ( String [ ] args ) { int X = 21 , K = 2 ; GFG g = new GFG ( ) ; System . out . print ( g . greatestKBits ( X , K ) ) ; } }