方案一:(只適合計算正數)ide
#include<stdio.h>spa
#include<stdlib.h>blog
int main()get
{it
int num = 10; //10的二進制數爲1010io
int count = 0;class
while (num)二進制
{float
if (num % 2 == 1) //從最高位開始除,餘數爲1則爲1,餘數爲2則爲0im
{
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