Write an algorithm to find F(n) the number of bits set to 1, in all numbers from 1 to n for any given value of n.
Complexity should be O(log n)
By the way, this question can also be done by the method of lookup table. Precompute the number of set bits from 0-255 and store it. Post that, we can calculate the number of set bits in any number by breaking a given number into two parts of 8 bits each. For each part, we can lookup in the count array formed in the first step. For example, if there is a 16 bit number like,
x = 1100110001011100, here, the number of set bits = number of set bits in the first byte + number of set bits in the second byte. Therefore, for obtaining, first byte,
y = (x & 0xff)
z = (x >> 8) & (0xff)
total set bits = count[y] + count[z]
This method will run in O(n) as well.