qfedu-basic-level/day9/homework/h10.cpp

69 lines
1.3 KiB
C++
Raw Permalink 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的个数及0的个数并返回结果。
#include <iostream>
#include <bitset>
using namespace std;
// 1 的个数
int countOne(int n)
{
int cnt = 0;
int temp = 0;
for (int i = 0; temp < n; i++)
{
temp = 1 << i;
if ((n & temp) == temp)
cnt++;
}
return cnt;
}
// 0 的个数
int countZero(int n)
{
int cnt = 0;
int temp = 0;
for (int i = 0; temp < n; i++)
{
temp = 1 << i;
if ((n | ~temp) == ~temp)
cnt++;
}
if (temp > n)
return cnt - 1;
return cnt;
}
// 逆向打印函数
void print(int n)
{
int temp = 0;
for (int i = 0; temp < n; i++)
{
temp = 1 << i;
if ((n & temp) == temp)
cout << "1"
<< " ";
if ((n | ~temp) == ~temp)
cout << "0"
<< " ";
}
cout << endl;
}
int main()
{
int x;
cout << "请输入一个整数: ";
cin >> x;
cout << x << " 的二进制表示为: " << bitset<12>(x) << endl;
cout << x << " 的我的二进制表示为: " << endl;
print(x);
cout << x << " 的二进制表示中 1 的个数为: " << countOne(x) << endl;
cout << x << " 的二进制表示中 0 的个数为: " << countZero(x) << endl;
return 0;
}