方案一:(只适合计算正数)
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num = 10; //10的二进制数为1010
int count = 0;
while (num)
{
if (num % 2 == 1) //从最高位开始除,余数为1则为1,余数为2则为0
{
count++; //余数为1时计数加1
}
num = num / 2; //除以2相当于右移一位,即丢掉计数过的
}
printf("%d\n", count);
system("pause");
return 0;
}
方案二:(正负数皆可)
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num = 10;
int count = 0;
while (num)
{
if ((num&1) == 1) //&按位与:有0则0,双1则1。即从最高位开始每位数字按位与1
{
count++;
}
num = num >> 1; //相当于除以2
}
printf("%d\n", count);
system("pause");
return 0;
}
方案三:(正负数皆可)
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned int num = -1; //-1的二进制数为11111111 11111111 11111111 11111111
int count = 0;
while (num)
{
if ((num&1) == 1)
{
count++;
}
num = num >> 1;
}
printf("%d\n", count);
system("pause");
return 0;
}
方案四:(正负数皆可)
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num = -1;
int count = 0;
while (num)
{
count++;
num = num&(num - 1);
}
printf("%d\n", count);
system("pause");
return 0;
}
结果:
num=10 //10的二进制数为1010
num=-1 //-1的二进制数为11111111 11111111 11111111 11111111