e.g.代码实现:一个整数存储在内存中的二进制中的1的个数
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int num = 0;
int count = 0;
printf("统计num的补码中有几个1,请输入num:>");
scanf("%d", &num);
//统计num的补码中有几个1
//法一
//while (num)//负数出错
//{
// if (num % 2 == 1)
// count++;
// num /= 2;
//}
//法二
int i = 0;
/*
32bit
num & 1 == 1
按位与,同为1才是1,右移不断按位与
*/
for (i = 0; i < 32; i++)
{
if (((num >> i) & 1) == 1)
{
/*
num & 1
num >> i
*/
count++;
}
//count++;
}
//法三
int i = 0;
int count = 0;
while (num)//num != 0
{
count++;
num = num & (num - 1);
/*以6为例,
num = 0110--->1
num - 1 = 0011
num = 0010--->2
num - 1 = 0001
num = 0000
*/
}
printf("%d\n", count);
}