算在十进制数的二进制格式的1的数 [英] Count number of 1's in binary format of decimal number
本文介绍了算在十进制数的二进制格式的1的数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找出1的数量在一个大的十进制数的二进制形式(10进制数可以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).
我想这块code的:
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);
}
这篇关于算在十进制数的二进制格式的1的数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文