#include <iostream>
#include <cstdlib>
int fun(int x);
int main()
{
std::cout << fun(9999) << std::endl;
return EXIT_SUCCESS;
}
int fun( int x )
{
int count(0);
while (x)
{
++count;
x = x&(x-1);
}
return count;
}//函数的功能:
x的二进制中包含1的数量
本文介绍了一个使用C++编写的简单程序,该程序通过位操作来计算一个整数在二进制表示下1的个数。这种方法不仅高效,而且避免了传统循环计算可能带来的性能问题。
#include <iostream>
#include <cstdlib>
int fun(int x);
int main()
{
std::cout << fun(9999) << std::endl;
return EXIT_SUCCESS;
}
int fun( int x )
{
int count(0);
while (x)
{
++count;
x = x&(x-1);
}
return count;
}x的二进制中包含1的数量

被折叠的 条评论
为什么被折叠?