Largest number less than X having at most K set bits | Function to get no of set bits in binary representation of positive integer n ; 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
function countSetBits ( n ) { let count = 0 ; while ( n > 0 ) { count += n & 1 ; n >>= 1 ; } return count ; } function greatestKBits ( X , K ) { let set_bit_count = countSetBits ( X ) ; if ( set_bit_count <= K ) return X ; let diff = set_bit_count - K ; for ( let i = 0 ; i < diff ; i ++ ) X &= ( X - 1 ) ; return X ; } let X = 21 , K = 2 ; document . write ( greatestKBits ( X , K ) ) ;