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.
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:
- 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.
C++
#include <bits/stdc++.h>
using namespace std;
typedef unsigned int uint_t;
uint_t nxtHighWithNumOfSetBits(uint_t x)
{
uint_t rightOne;
uint_t nextHigherOneBit;
uint_t rightOnesPattern;
uint_t next = 0;
if (x) {
rightOne = x & -( signed )x;
nextHigherOneBit = x + rightOne;
rightOnesPattern = x ^ nextHigherOneBit;
rightOnesPattern = (rightOnesPattern) / rightOne;
rightOnesPattern >>= 2;
next = nextHigherOneBit | rightOnesPattern;
}
return next;
}
int mthSmallestWithKSetBits(uint_t m, uint_t k)
{
uint_t num = (1 << k) - 1;
for ( int i = 1; i < m; i++)
num = nxtHighWithNumOfSetBits(num);
return num;
}
int main()
{
uint_t m = 6, k = 4;
cout << mthSmallestWithKSetBits(m, k);
return 0;
}
|
Java
Python3
C#
Javascript
Output:
39
Time Complexity: O(m)
Space Complexity: O(1)
Last Updated :
17 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...