Given two non-negative integers m and k. The problem is to find the m-th smallest number having k number of set bits.
Constraints: 1 <= m, k.
Input : m = 4, k = 2 Output : 9 (9)10 = (1001)2, it is the 4th smallest number having 2 set bits. Input : m = 6, k = 4 Output : 39
Approach: Following are the steps:
- Find the smallest number having k number of set bits. Let it be num, where num = (1 << k) – 1.
- Loop for m-1 times and each time replace num with the next higher number than ‘num’ having same number of bits as in ‘num’. Refer this post to find the required next higher number.
- Finally return num.
Time Complexity: O(m)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find the smallest number with n set and m unset bits
- Smallest number whose set bits are maximum in a given range
- Check if bits of a number has count of consecutive set bits in increasing order
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Check if a number has same number of set and unset bits
- Toggle bits of a number except first and last bits
- Number of integers with odd number of set bits
- Minimum number using set bits of a given number
- Next higher number with same number of set bits
- Same Number Of Set Bits As N
- Set all odd bits of a number
- Set all even bits of a number
- Largest number less than X having at most K set bits
- Check whether the number has only first and last bits set
- Toggle all even bits of a number
Improved By : SHUBHAMSINGH10