第一种方法
#include<stdio.h>
int count_num_of_1(unsigned int n)
{
int count=0;
while(n)
{
if((n%2)==1)
{
count++;
}
n=n/2;
}
return count;
}
int main()
{
int n=0;
scanf("%d",&n);
int num=count_num_of_1(n);
printf("%d",num);
return 0;
}
第二种方法
#include<stdio.h>
int count_num_of_1(int n)
{
int count=0;
while(n)
{
n=n&(n-1);
count++;
}
return count;
}
int main()
{
int n=0;
scanf("%d",&n);
int num=count_num_of_1(n);
printf("%d",num);
return 0;
}