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

后端 未结 16 2118
轻奢々
轻奢々 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:16

    If n= 2^k-1, then F(n)=k*(n+1)/2

    For a general n, let m be the largest number such that m = 2^k-1 and m<=n. F(n) = F(m) + F(n-m-1) + (n-m).

    Corner condition: F(0)=0 and F(-1)=0.

提交回复
热议问题