Problem Description:
Enter an integer of type A to calculate the number of 1 in the binary storage mode in this digit.
Program Analysis:
1. The input integer A is stored in a binary form in the computer, and the method we use is a bitwise judgment.
2. When the number a is greater than 0 o'clock, the number and the 1 phase (bitwise), if the phase of the result is 1, the current is 1, the predefined count plus 1 is defined, and the number is shifted to the right one to be judged in the same way. The value of the output count.
The code is as follows:
/********************* calculates the number of 0 in a binary number *******************/
#include <stdio.h>
void count_one (int a) //define a Count_one function
{
int count = 0;//defines a count used to record 1, and is initialized to 0 while
(a > 0) //Judging when a>0 enters the following loop
{if (
(A & 1) = = 1) //Use bitwise AND to determine whether the minimum bit of binary is 1
{
++count; If yes, add 1
}
a = a>>1; Move a right one bit to determine bits
("%d\n", count) at
the front of the first bit;
int main ()
{
int flag = 1;
int b;
while (flag)
{
printf ("Please input an intger number:\n");
scanf ("%d", &b);
Count_one (b);//Call the Count_1 function and output the result to
printf ("Continue:1 break:0\n");
scanf ("%d", &flag);
}
return 0;
}