The first method, which is easy to think of, is module 2 division 2 method. The modulo 2 operation gets the lowest bit in the binary sequence of the number, and the Division 2 removes the lowest bit in the binary sequence of the number. When the result of modulo-2 operation of this number is 1, then its lowest bit is 1, and then divide it by 2, and set the number of the penultimate bit as the last bit. If this number is 0, then we can judge whether each bit is 1. At the same time, it should be noted that this method can only judge positive numbers, not negative numbers, because the result of modulo 2 operation of negative numbers can only be 0, which is a major defect of this method. The following is the specific implementation code:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
//This method can't judge negative number because the result of negative number modulo 2 is always 0
int count_one_bits(int n)
{
int count = 0;
while (n)
{
if (n % 2 == 1)//If the result of module 2 is 1, it will count++
{
count++;
}
n = n / 2;//Divide by 2 to remove the last digit
}
return count;
}
int main()
{
int i = 0;
int num = 0;
scanf("%d", &num);
int ret = count_one_bits(num);//Pass the argument num into the function
printf("%d\n", ret);
system("pause");
return 0;
}
The second method is to perform bitwise sum of the number and 1. If the result is 1, then the last bit of the number is 1. After judging the last bit, move the number to the right, and then judge the penultimate bit. After 32 cycles, you can determine how many digits 1 are in the binary sequence of the number. This method makes up the defect that modulo 2 division 2 method can only judge positive numbers. The following is the specific implementation code:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int count_one_bits(int n)
{
int count = 0;
int i = 0;
for (i = 0; i < 32; i++)
{
if ((n >> i) & 1 == 1)//If a number and 1 are bitwise and the result is 1, the last bit of the number is 1
{
count++;
}
}
return count;
}
int main()
{
int num = 0;
scanf("%d", &num);
int ret = count_one_bits(num);//Pass the argument num into the function
printf("%d\n", ret);
system("pause");
return 0;
}
The third method is also an optimization method, that is, the number to be judged and the number minus one are bitwise and assigned to the number, and then cycle like this until the number is 0, so that you can judge how many digits 1 are divided by the binary sequence of the number. The specific implementation code is as follows:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int count_one_bits(int n)
{
int count = 0;
while (n)
{
n = n & (n - 1);
count++;
}
return count;
}
int main()
{
int num = 0;
scanf("%d", &num);
int ret = count_one_bits(num);//Pass the argument num to the function
printf("%d\n", ret);
system("pause");
return 0;
}