以十进制数的二进制格式计算 1 的个数

2022-01-09 00:00:00 binary decimal c++

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

I am trying to find out the number of 1's in binary form of a large decimal number (decimal number can be as large as 1000000).

我试过这段代码:

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

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

I want a faster algorithm as it takes long time for large decimal input. Please suggest me an efficient algorithm.

推荐答案

在 C++ 中你可以这样做.

In C++ you can just do this.

#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);
}

相关文章