To find the number of binary 1 of a number
1, through the method of modular removal
#define _crt_secure_no_warnings 1
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i = 0;
int count = 0;
printf ("Please enter a number: \ n");
scanf ("%d", &i);
while (i)
{
if (i%2==1)
{
count++
}
i = I/2;
}
printf ("Number of 1 in this number is:%d 1\n", count);
}
2, but this will be flawed, if you enter a negative, the control of the symbol is not very good
Write it in a separate function and pass it into unsigned int num to resolve
#define _crt_secure_no_warnings 1
#include <stdio.h>
#include <stdlib.h>
int count _one_bits (unsigned int num)
{
int count = 0;
while (num)
{
if (num%2 = 1)
{
count++
}
num = NUM/2;
}
return count;
}
int main ()
{
int num = one;
int result = 0;
result = Count_one_bits (num);
printf ("Number of 1 in this number is:%d 1\n", result);
return 0;
}
3, because the general number of bits are 32 bits, there may not be complete statistics of the number of 1, with the loop to solve
#define _crt_secure_no_warnings 1
#include <stdio.h>
#include <stdlib.h>
int count_one _bits (unsigned int num)
{
int count = 0;
int i = 0;
For (I=1 i<32; i++)
{
if (num%2 = = 1)
{
count++;
}
num = NUM/2;
}
return count;
}
int main ()
{
int num = 0;
int result = 0;
printf ("Please enter a number: \ n");
scanf ("%d", &num);
result = Count_one_bits (num);
printf ("%d of the binary number of 1 of the number is:%d 1\n", num,result);
return 0;
}
4, the number of cycles is 32 times, so that the program is a bit slow, and the method can be a good solution
#define _crt_secure_no_warnings 1
#include <stdio.h>
#include <stdlib.h>
int count_one _bits (unsigned int num)
{
int count = 0;
while (num)
{
num = num& (num-1);
count++;
}
return count;
}
int main ()
{
int num = 0;
int result = 0;
printf ("Please enter a number: \ n");
scanf ("%d", &num);
result = Count_one_bits (num);
printf ("%d of the binary number of 1 of the number is:%d 1\n", num,result);
return 0;
}