Find the number of 1s in an integer stored in binary
Integer is a decimal number. Converting it to a binary number will result in a 32-bit binary number. For
example, 00000000000000000000000000001011.
We can move the binary number continuously to think and compare it to the previous 1, so that as long as the result of each and 1 is 1, this bit The in-position 1
is calculated by count++, otherwise it is 0.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 0;
int count = 0;
scanf("%d", &num);
int i = 0;
for (i = 0; i<32; i++)
{
if (1 == ((num >> i) & 1))
count++;
}
printf("%d\n", count);
system("pause");
return 0;
}
2. Although we have written the code we want, it has to be run 32 times each time, is it a bit troublesome?
Let’s optimize
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 0;
printf("请输入一个整数:");
scanf("%d", &num);
int i = 0;
int count = 0;
while (num)
{
count++;
num = num&(num - 1);
}
printf("它在二进制中1的个数 = %d\n", count);
system("pause");
return 0;
}
thanks for watching!