69 lines
1.3 KiB
C++
69 lines
1.3 KiB
C++
// 编写一个函数,用于计算一个整数的二进制表示中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;
|
||
} |