【问题标题】:Algorithm to count "1" digits in binary representation of a numbers from a to b [duplicate]从a到b的数字的二进制表示中计算“1”位的算法[重复]
【发布时间】:2015-03-21 21:18:56
【问题描述】:

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

其中 0

【问题讨论】:

  • @πάνταῥεῖ ῥεῖ 怎么样?你能解释一下吗?
  • @James Rodrigues AFAIK 在 C++ 和 C 中没有可以包含值 10 ^16 的整数类型。:) 所以出现了一个问题,什么类型的对象包含如此大数字的二进制表示和数字本身是什么类型的?
  • >在 C++ 和 C 中没有可以包含值 10 ^16 的整数类型

标签: c++ algorithm


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多