Largest number less than X having at most K set bits | C ++ 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
#include <iostream> NEW_LINE using namespace std ; int greatestKBits ( int X , int K ) { int set_bit_count = __builtin_popcount ( 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 ; } int main ( ) { int X = 21 , K = 2 ; cout << greatestKBits ( X , K ) ; return 0 ; }