VOOZH about

URL: https://www.geeksforgeeks.org/dsa/m-th-smallest-number-k-number-set-bits/

⇱ M-th smallest number having k number of set bits. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

M-th smallest number having k number of set bits.

Last Updated : 17 Mar, 2023

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.
Examples: 
 

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:
 

  1. Find the smallest number having k number of set bits. Let it be num, where num = (1 << k) - 1.
  2. 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.
  3. Finally return num.


 

Output: 
 

39


Time Complexity: O(m)

Space Complexity: O(1)
 

Comment
Article Tags: