计算算法" 1"从a到b的数字的二进制表示中的数字

时间:2015-03-21 08:13:01

标签: c++ algorithm

如何计算从a到b的数字的二进制表示中的“1”数字。

其中0 < a&lt; = b&lt; 10 ^ 16

1 个答案:

答案 0 :(得分:1)

要找到任务P [a..b]的解,你必须找到子问题P [0..b]和P [0..a]的解,并减去这些值。
现在考虑P [0..x]任务。简单情况x = 2 ^ k(100..000bin)。

0th bit is set in 2^k/2 numbers (it alternates every time)
1th bit is set in 2^k/2 numbers (it alternates after pair of numbers)
..
k-1th bit is set in 2^k/2 numbers (in 2^(k-1)..(2^k)-1))
kth bit is set in one number (in 2^k)

所以

P[0..2^k] = k * 2^(k-1) + 1

要找到任意x的解,我们可以利用x的二进制表示,例如:
P(1010b) = P(1000b) + P(10b)

伪代码

P = 0
k = 0 
while x <> 0 do
   if (x and 1) then //check if kth bit is set in x
       P = P + k * 2^(k-1) + 1 
   x = x >> 1  //shift right
   k = k + 1