Finding the total number of set-bits from 1 to n

后端 未结 16 2106
轻奢々
轻奢々 2020-12-04 09:54

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)

16条回答
  •  悲&欢浪女
    2020-12-04 10:27

    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.

提交回复
热议问题