利用短除法原理实现代码
#include <stdio.h>
int conut_bit_one(unsigned m) //将m变为一个无符号数;
{
int count = 0;
while (m)
{
if (m % 2 == 1)
{
count++;
}
m = m / 2;
}
return count;
}
int main()
{
int t = 0;
scanf_s("%d", &t);
int count =conut_bit_one(t);
printf("%d\n", count);
return 0;
利用位操作符和移位操作符实现代码
{
//11111111111111111111111111111111 =a
//00000000000000000000000000000001 =b
//00000000000000000000000000000001 将a&b(&按位与运算:有0则0),判断得到的结果是否为1,为1则count++。
}
#include <stdio.h>标签:count,00000000000000000000000000000001,return,二进制,个数,++,整数,int,conut From: https://blog.51cto.com/u_15938145/6024961
int conut_bit_one(int m)
{
int count = 0;
int i = 0; //用i来控制按位与的循环停止
for (i = 0; i < 32; i++)
{
if (((m >> i) & 1) == 1)
//11111111111111111111111111111111 =a
//00000000000000000000000000000001 =b
//00000000000000000000000000000001 将a&b(&按位与运算:有0则0),判断得到的结果是否为1,为1则count++。
{
count++;
}
}
return count;
}
int main()
{
int t = 0;
scanf_s("%d", &t);
int count =conut_bit_one(t);
printf("%d\n", count);
return 0;
}