方法一:
程序:
#include<stdio.h>
int  count_one_bits(int t)
{
int i = 32;
int count = 0;
while (i>0)
{
if (t & 1 == 1)
{
count++;
}
//t=t/2
t = t >> 1;
i -= 1;
}
return count;
}
int main()
{
int t = 0;
printf("请输入一个整数:");
scanf("%d", &t);
int  ret=count_one_bits(t);
printf("count=%d\n", ret);
return 0;
}
方法二:
程序:
#include<stdio.h>
int  count_one_bits(int t)
{
int count = 0;
while (t)
{
count++;
t = t&(t - 1);
//最低位为1,其余全为0,循环效率高,有几个1就循环几次
}
return count;
}
int main()
{
int t = 0;
printf("请输入一个整数:");
scanf("%d", &t);
int  ret=count_one_bits(t);
printf("count=%d\n", ret);
return 0;
}
结果一:
请输入一个整数:15
count=4
请按任意键继续. . .
 
结果二:
请输入一个整数:-2
count=31
请按任意键继续. . .