qfedu-basic-level/day7/homework/h11.cpp

24 lines
576 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 使用位运算符实现以下条件:判断一个数的二进制表示中有多少个 1
// 例如:输入 5输出 2 : 5 的二进制表示为 101其中有 2 个 1
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
int n;
cout << "请输入一个整数: ";
cin >> n;
int cnt = 0; // 计数器
while (n)
{
if (n & 1)
cnt++; // 如果 n 的最后一位是 1计数器加 1
n >>= 1; // n 右移一位
}
cout << "二进制表示中有 " << cnt << " 个 1" << endl;
return 0;
}