求一个数的二进制的1的个数
1,通过模除的方法
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i = 0;
int count = 0;
printf("请输入一个数字:\n");
scanf("%d",&i);
while(i)
{
if(i%2==1)
{
count++;
}
i = i/2;
}
printf("这个数中1的个数为:%d个1\n",count);
}
2,但是这样会有缺陷,如果输入一个负数的话,对于符号为的控制就不是很好
将其单独写成一个函数,并且传进去成unsigned int num,可以解决
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int count_one_bits(unsigned int num)
{
int count = 0;
while(num)
{
if(num%2 == 1)
{
count++;
}
num = num/2;
}
return count;
}
int main()
{
int num = 11;
int result = 0;
result = count_one_bits(num);
printf("这个数中的1的个数为:%d个1\n",result);
return 0;
}
3,由于一般的数的二进制位都是32位,有可能不能完全的统计1的个数,用循环来解决
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int count_one_bits(unsigned int num)
{
int count = 0;
int i = 0;
for(i=1; i<32; i++)
{
if(num%2 == 1)
{
count++;
}
num = num/2;
}
return count;
}
int main()
{
int num = 0;
int result = 0;
printf("请输入一个数:\n");
scanf("%d",&num);
result = count_one_bits(num);
printf("%d的二进制数中1的个数为:%d个1\n",num,result);
return 0;
}
4,循环的次数是32次,这样程序就有些慢,改用与的方法就可以很好地解决
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int count_one_bits(unsigned int num)
{
int count = 0;
while(num)
{
num = num&(num-1);
count++;
}
return count;
}
int main()
{
int num = 0;
int result = 0;
printf("请输入一个数:\n");
scanf("%d",&num);
result = count_one_bits(num);
printf("%d的二进制数中1的个数为:%d个1\n",num,result);
return 0;
}