C++ bitset count()函数用于对数字的二进制表示形式中的设置位数进行计数。
int count();
它以整数值返回设置位数。
#include <iostream> #include <bitset> using namespace std; int main() { bitset<4> b1(string("1100")); int result=b1.count(); cout<<b1 << " has" <<' ' << result <<" bits"; return 0; }
输出:
1100 has 2 bits
#include <iostream> #include <bitset> using namespace std; int main() { bitset<4> b1(16); bitset<4> b2(18); int result=b1.count(); int result1=b2.count(); cout<<b1 << " has" <<' ' << result <<" set bits" << '\n'; cout<<b2 << " has" <<' ' << result1 <<" set bits"; return 0; }
输出:
0000 has 0 set bits 0010 has 1 set bits
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)