1:我们知道,整数在计算机中是以补码的形式存储的。如果给定一个十进制正整数是 如何转换成二进制数的呢?用的是除以2取余数的方法。若余数为1,则1的个数加 1;然后用商再除以2取余数,直到商为0;但是负数除2的余数为负数。因此,可以 在用 unsigned int 定义一个整数,将有符号数转换成无符号数。例如-1的补码 为11111111 11111111 11111111 11111111。用unsigned定义11111111 11111111 11111111 11111111表示的不再是-1,而是2^32-1。但这不影响1的个数。
具体代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25#include <stdio.h> int count_one_bits(unsigned int value) { int count = 0; while (value) { if (1 == value%2) { count++; } value = value/2; } return count; } int main() { int input; int c = 0; scanf("%d", &input); c = count_one_bits(input); printf("数的二进制表示中1的个数为:%dn", c); return 0; }

2:1的二进制位00000000 00000000 00000000 00000001,a&1则可判断的最低位 是0还是1,同样需要使用unsigned。每进行一次按位与运算,还要将a右移一位。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25#include <stdio.h> int count_one_bits(unsigned int value) { int count = 0; while (value) { if ((value&1) == 1) { count++; } value = value>>1; } return count; } int main() { int input; int c = 0; scanf("%d", &input); c = count_one_bits(input); printf("数的二进制表示中1的个数为:%dn", c); return 0; }
3:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22#include <stdio.h> int count_one_bits(int value) { int count = 0; while (value) { count++; value = value&(value-1); } return count; } int main() { int input; int c = 0; scanf("%d", &input); c = count_one_bits(input); printf("数的二进制表示中1的个数为:%dn", c); return 0; }

最后
以上就是迷人小蝴蝶最近收集整理的关于C语言求一个整数的二进制形式表示中1的个数,用函数实现的全部内容,更多相关C语言求一个整数内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复