输入一个数 输出二进制中1和0的个数
时间: 2024-06-14 12:08:38 浏览: 13
以下是两种方法来输出二进制中1和0的个数:
1. 使用位运算符来计算二进制中1的个数[^1]:
```c
#include <stdio.h>
int cnt;
int main() {
int x;
scanf("%d",&x);
while(x){
if(x&1) cnt++;
x=x>>1;
}
printf("1的个数:%d\n",cnt);
printf("0的个数:%d\n",sizeof(int)*8-cnt);
return 0;
}
```
2. 使用位运算符和循环来计算二进制中1的个数[^2]:
```c
#include <stdio.h>
int main() {
int x;
scanf("%d",&x);
int count = 0;
while (x != 0) {
count += x & 1;
x >>= 1;
}
printf("1的个数:%d\n", count);
printf("0的个数:%d\n", sizeof(int)*8-count);
return 0;
}
```
相关问题
c++输入一个数 ,将数字转换成二进制,输出二进制中1和0的个数
以下是一个C++程序,可以将输入的数字转换成二进制,并输出二进制中1和0的个数[^1]:
```cpp
#include <iostream>
#include <bitset>
using namespace std;
int main() {
int num;
cout << "请输入一个整数:";
cin >> num;
bitset<32> binary(num);
string binaryStr = binary.to_string();
int count0 = 0;
int count1 = 0;
for (char c : binaryStr) {
if (c == '0') {
count0++;
} else if (c == '1') {
count1++;
}
}
cout << num << "对应的二进制数为:" << binaryStr << endl;
cout << num << "对应的二进制数中0和1的个数分别为:" << count0 << " " << count1 << endl;
return 0;
}
```
运行程序后,会要求输入一个整数,然后将该整数转换成二进制,并输出二进制中0和1的个数。
输入一个整数,输出其二进制中1的个数
您好,对于您的问题,我可以提供以下代码:
```python
def count_bits(n):
count = 0
while n:
count += n & 1
n >>= 1
return count
```
这个函数接收一个整数作为参数,然后使用位运算来计算其二进制中1的个数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)