Find the number of binary 1s for integers in C language daily questions

insert image description here

Share a question today, use three methods to solve
the number of binary 1

Method 1.
We can divide our decimal system by 10 and take the remainder to get our numbers for each digit, so our binary system can
also

#include<stdio.h>
int num_find_1(unsigned int n)
{
    
    
	int count = 0;
	while (n)
	{
    
    
		if (1 == n % 2)
		{
    
    
			count++;
		}
		n /= 2;
	}
	return count;
}
int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	int ret = num_find_1(n);
	printf("%d", ret);
	return 0;
}

This is one method, the other is that we can use the shift operator to calculate

int num_find_1(int n)
{
    
    
	int i = 0;
	int count = 0;
	for (i = 0; i < 32; i++)
	{
    
    
		if (((n >> i) & 1) == 1)
		{
    
    
			count++;
		}
	}
	return count;
}
int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	int ret = num_find_1(n);
	printf("%d", ret);
	return 0;
}



Isn’t this method particularly wonderful, of course there are better ways, please see! ! !


int num_find_1(int n)
{
    
    
	int i = 0;
	int count = 0;
	while (n)
	{
    
    
		n = n & (n - 1);
		count++;
	}
	return count;
}
int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	int ret = num_find_1(n);
	printf("%d", ret);
	return 0;
}



I believe that after reading it, I will always learn a method. Today’s sharing is here. I don’t know if you have noticed that my beginning is different, hehe.

Guess you like

Origin blog.csdn.net/2301_76895050/article/details/131987982