让我们将F(n)定义为
F(n) = total set bits in binary representation of 0 to (2^n) -1.
Eg:
F(1) = number of bits set in 0 + number of bits set in 1 = 1
F(2) = number of bits set in 0 + ...... number of bits set in 3 = 4
是否有O(log n)算法来计算F(n),其中n可以大到10 ^ 6.
答案 0 :(得分:2)
如果要求在0到2 n -1的所有整数的二进制表示中设置的位数,则很简单:
请记住在您的作业中引用此网页:v)。
答案 1 :(得分:0)
我闻到了作业,所以我遗漏了代码
一个简单的解决方案,使用对于第i个最低有效位,答案将是
的事实(N/2^i)*2^(i-1)+ X
where X = N%(2^i) - (2^(i-1)-1) iff N%(2^i)>=(2^(i-1)-1)
考虑从1到N的数字的第i个最低有效位(基于1的索引),然后它们以等于2 ^ i的周期重复。在该时段中,前半部分的值为0,下半部分为0例如: - 对于从0到7的数字,(0将没有贡献,所以没有效果)
000
001
010
011
100
101
110
111
1st least significant bit = 01010101 Period=2
2nd least significant bit = 00110011 Period=4
3rd least significant bit = 00001111 Period=8
and so on.
So for the ith least significant bit ,answer will be (N/Period)*(Half of Period Size) + (N%(2^i - 1) - Half of Period Size + 1)
The second term will only be taken when N%Remainder is greater than or equal to Half of Period Size.
Also , N%(2^i) can be written as N&(2^i - 1)