M-th smallest number having k number of set bits.
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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
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 write.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.