相关疑难解决方法(0)

在某个位置或更低位置计算设置位的有效方法是什么?

给定std::bitset<64> bits任意数量的位和位位置X(0-63)

在X位或更低位计数位的最有效方法是什么,如果未设置X位,则返回0

注意:如果设置该位,则返回始终至少为1

蛮力方式很慢:

int countupto(std::bitset<64> bits, int X)
{
  if (!bits[X]) return 0;
  int total=1;
  for (int i=0; i < X; ++i)
  {
    total+=bits[i];
  }
  return total;
}
Run Code Online (Sandbox Code Playgroud)

这个count()方法bitset将为您popcount提供所有位,但bitset不支持范围

注意:这不是如何计算32位整数中的设置位数?因为它询问所有位而不是0到X的范围

c++ algorithm performance bit-manipulation

33
推荐指数
4
解决办法
5006
查看次数

标签 统计

algorithm ×1

bit-manipulation ×1

c++ ×1

performance ×1