int total1(int n)
{
if(n==0) return 0;int x=n,count=0;
while(x)
{
x=x&(x-1);
count ++;
}
}
解析:x&(x-1) 有一个特点,x-1会使原本x最右边的那个1变为0,再相与则将最右边的1去掉了,且每次去掉一个,最终x=0.
#include "stdio.h"
int total1(int n)
{
if (!n) return 0;
int x=n,count =0;
while (x)
{
x=x&(x-1);
count++;
}
}
void main(void)
{
int a,t;
printf("请输入一个整数,将计算它的二进制中包含1的个数!\n");
do
{
t=scanf("%d",&a);
while(getchar()!='\n'){}; /*用循环把缓冲区的不匹配字符读完*/
if(t==0)
{
printf("非法输入,只允许输入整数!\n");
}
}
while(t==0);
printf("整数%d的二进制中1的个数为:%d\n",a,total1(a));
getchar();
}