Here is an algorithm (written in C) to find the n-th integer with k
one bits...
int NthIntWithKOneBits(int n, int k)
{
int i, iCk, result=0;
if( n == 1 && k == 0 ) return 0;
if( n <= 0 || k <= 0 ) return -1;
while( n > 0 && k > 0 )
{
i = k;
iCk = 1;
while( iCk < n )
{
i++;
iCk = iCk * i / (i - k);
}
result |= 1 << i-1;
n -= iCk * (i - k) / i;
k--;
}
return result | (1 << k) - 1;
}
Dave
On Aug 27, 1:58 am, ankur aggarwal <[email protected]> wrote:
> Nth number with K set bits
> We are given with k number of set bits (bit=1). We have to find the Nth
> number which has k set bits.
>
> for example
>
> k=3
>
> the numbers with k set bits are as follows:
>
> 000111 = 7
> 001011 = 11
> 001101 = 13
> 001110 = 14
> 010011 = 19
> 010101 = 21
> 010110 = 22
> 011001 = 25
> 011010 = 26
> 011100 = 28
> ....
> and so on....
>
> we have to find the Nth number in this series...
>
> suggest some method
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at http://groups.google.com/group/algogeeks
-~----------~----~----~----~------~----~------~--~---