I found this question here, but this is not the answer i am looking for. Hence, posting again.
A function of the form:
F( N ) = rank
means that Given a number N in decimal representation, its rank is given as:
Starting from 0 to N, how many numbers are there with same number of set bits in its
binary representation.
I will go through an example to make it more clear.
N = 6 ( 0110 )
Its rank is 3.
1. 3 ( 0011 )
2. 5 ( 0101 )
3. 6 ( 0110 )
Now, given a number, find its rank.
The obvious approach is to start from 0 and check for number of set bits for each number till N-1.
The question is:
Is there any logN solution?
Yes, there is a
log nsolution.Let
nhavekbits set, the most significant bit being in positionp(starting to count positions from 0, so2^p <= n < 2^(p+1)). Then there arepCk(binomial coefficient, alsochoose(p,k)) ways to placekbits in the positions0, ..., p-1, all these give numbers with exactlykset bits that are smaller thann. Ifk == 1, that’s it, otherwise there remain the numbers withkset bits and thep-th bit set that are smaller thannto consider. Those can be counted by determining the rank ofn - 2^p.Code (not optimal, does some unnecessary recomputation, and doesn’t all that it could do to avoid overflow):
Tested in a loop for
0 <= n < 10^8to check for mistakes without any mismatch found.Check output here.