计数十进制数的二进制格式的1

zal*_*nix 5 c++ binary decimal

我试图找出大十进制数的二进制形式的1的数量(十进制数可以大到1000000).

我尝试了这段代码:

while(sum>0)  
{  
    if(sum%2 != 0)  
    {  
        c++;   // counting number of ones  
    }  
    sum=sum/2;  
}  
Run Code Online (Sandbox Code Playgroud)

我想要一个更快的算法,因为大十进制输入需要很长时间.请建议我一个有效的算法.

tro*_*foe 19

您正在寻找的是"popcount",它在以后的x64 CPU上作为单个CPU指令实现,不会因为速度而被打败:

#ifdef __APPLE__
#define NAME(name) _##name
#else
#define NAME(name) name
#endif

/*
 * Count the number of bits set in the bitboard.
 *
 * %rdi: bb
 */
.globl NAME(cpuPopcount);
NAME(cpuPopcount):
    popcnt %rdi, %rax
    ret
Run Code Online (Sandbox Code Playgroud)

但是,当然,您需要首先测试CPU是否支持它:

/*
 * Test if the CPU has the popcnt instruction.
 */
.globl NAME(cpuHasPopcount);
NAME(cpuHasPopcount):
    pushq %rbx

    movl $1, %eax
    cpuid                   // ecx=feature info 1, edx=feature info 2

    xorl %eax, %eax

    testl $1 << 23, %ecx
    jz 1f
    movl $1, %eax

1:
    popq %rbx
    ret
Run Code Online (Sandbox Code Playgroud)

这是C中的一个实现:

unsigned cppPopcount(unsigned bb)
{
#define C55 0x5555555555555555ULL
#define C33 0x3333333333333333ULL
#define C0F 0x0f0f0f0f0f0f0f0fULL
#define C01 0x0101010101010101ULL

    bb -= (bb >> 1) & C55;              // put count of each 2 bits into those 2 bits
    bb = (bb & C33) + ((bb >> 2) & C33);// put count of each 4 bits into those 4 bits
    bb = (bb + (bb >> 4)) & C0F;        // put count of each 8 bits into those 8 bits
    return (bb * C01) >> 56;            // returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ...
}
Run Code Online (Sandbox Code Playgroud)

GNU C编译器运行时包含一个"内置",它可能比上面的实现更快(它可能使用CPU popcnt指令,但这是特定于实现的):

unsigned builtinPopcount(unsigned bb)
{
    return __builtin_popcountll(bb);
}
Run Code Online (Sandbox Code Playgroud)

所有上述实现都在我的C++国际象棋库中使用,因为当使用位板来表示棋子位置时,popcount在国际象棋移动生成中起着至关重要的作用.我在库初始化期间使用函数指针设置指向用户请求的实现,然后通过该指针使用popcount函数.

Google将提供许多其他实现,因为它是一个有趣的问题,例如:http://wiki.cs.pdx.edu/forge/popcount.html.


Rap*_*ptz 19

在C++中,您可以这样做.

#include <bitset>
#include <iostream>
#include <climits>

size_t popcount(size_t n) {
    std::bitset<sizeof(size_t) * CHAR_BIT> b(n);
    return b.count();
}

int main() {
    std::cout << popcount(1000000);
}
Run Code Online (Sandbox Code Playgroud)


BЈо*_*вић 12

有很多方法.Brian Kernighan的方式易于理解且速度非常快:

unsigned int v = value(); // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
  v &= v - 1; // clear the least significant bit set
}
Run Code Online (Sandbox Code Playgroud)