#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int count(int i){
int count=0;
while (i){
++count;
i=(i-1)&i;
}
return count;
}
int main(){
int i;
while (cin>>i){
cout<<count(i)<<endl;
}
}
本文介绍了一个使用位运算来统计整数中1的个数的算法,并提供了完整的C++实现代码。该方法通过不断清除最低位的1并计数,直到整数变为0。这是一种高效且实用的技术,适用于需要频繁进行此类操作的应用场景。
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int count(int i){
int count=0;
while (i){
++count;
i=(i-1)&i;
}
return count;
}
int main(){
int i;
while (cin>>i){
cout<<count(i)<<endl;
}
}

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