VOOZH about

URL: https://www.geeksforgeeks.org/dsa/largest-number-less-than-equal-to-n-having-exactly-k-set-bits/

⇱ Largest number less than equal to N having exactly K set bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest number less than equal to N having exactly K set bits

Last Updated : 15 Oct, 2023

Given two positive integers N and K, we need to determine if there exists a positive integer X less than or equal to N such that the number of 1s in the binary representation of X is equal to k (i.e., f(X) = K). If such an X exists, we also need to find the maximum value of X and print -1 if there is no such positive integer X.

Constraints:

1 <= X <=109
0 <= K <= 31

Examples:

Input: X = 8, K = 2
Output:6

Input: X = 9, K = 4
Output: -1

Approach: Follow the steps to solve the problem:

  • Count the number of set bits in the integer X.
  • If a number of set bits is equal to K then return that number itself.
  • Else traverse every bit of the number.
  • If the number of set bits in X is less than the required set bits (K).
  • Then count the number of non set bits we have to convert from the current bit and toggle them.
  • Else count the number of set bits we have to convert from 1's to 0's and toggle them from right to left.
  • If no such number is possible to create return -1.
  • Else return that maximum number which is less than X and has total K set bits.

Below is the implementation for the above approach:


Output
6
-1


Time Complexity: O(Log(N))
Auxiliary Space: O(1)

Comment