Scenario One: (only suitable for calculating positive numbers)
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int num = 10; 10 binary number is 1010
int count = 0;
while (NUM)
{
if (num% 2 = = 1)//start with the highest bit, the remainder is 1 is 1, the remainder is 2 is 0
{
count++; Remainder is 1 o'clock count plus 1
}
num = NUM/2; Dividing by 2 is equivalent to moving one bit to the right, i.e. losing the counted
}
printf ("%d\n", count);
System ("pause");
return 0;
}
Scenario Two: (positive negative number can be)
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int num = 10;
int count = 0;
while (NUM)
{
if ((num&1) = = 1)//& bitwise AND: There are 0 0, and the double 1 is 1. That is, starting from the highest bit, each digit is bitwise AND 1.
{
count++;
}
num = num >> 1; Equivalent to dividing by 2.
}
printf ("%d\n", count);
System ("pause");
return 0;
}
Scenario Three: (positive negative number can be)
#include <stdio.h>
#include <stdlib.h>
int main ()
{
unsigned int num =-1; -1 binary number is 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;
}
Scheme four: (positive negative number can be)
#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;
}
Results:
The binary number of num=10//10 is 1010
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7A/00/wKiom1agdxnQh4aeAAAPmB9nL-o018.png "style=" float: none; "Title=" counts the number of 1 in a binary number. png "alt=" Wkiom1agdxnqh4aeaaapmb9nl-o018.png "/>
Num=-1//-1 binary number is 11111111 11111111 11111111 11111111
650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/79/FF/wKioL1agd1bQERLRAAAP0aHoVUQ042.png "style=" float: none; "title=" statistics. png "alt=" Wkiol1agd1bqerlraaap0ahovuq042.png "/>
Count the number of 1 in the binary (four scenarios)