#include <stdio.h>
int statistics1(unsigned int num)
{
int count = 0;
while (num)
{
if (num % 2 == 1)
{
count++;
}
num /= 2;
}
return count;
}
int statistics2(int num)
{
int count = 0;
for (int i = 0; i < 32; i++)
{
if (((num >> i) & 1) == 1)
count++;
}
return count;
}
int statistics3(int num)//效率最高的方法
{
int count = 0;
while (num)
{
//例如:13
num = num & (num - 1); //1101&1100==1100
//1100&1011==1000
//1000&0111==0000
//每进行一次按位与操作 num二进制就少一位1.
count++;
}
return count;
}
int main()
{
int num = -1;
int b = statistics1(num);
int c = statistics2(num);
int d = statistics3(num);
printf("%d %d %d", b, c, d);//32 32 32
}
C语言 求一个整数存储在内存中的二进制中1的个数。
猜你喜欢
转载自blog.csdn.net/weixin_45275802/article/details/112534505
今日推荐
周排行