统计二进制中1的个数的三种解法(C语言)

写一个函数返回参数二进制中 1 的个数。

比如: 15    0000 1111    4 个 1

 解法1

先%2,再/2,直到为0

//15%2=1 1111
//15/2=7 0111
//7%2=1 
//7/2=3  0011
//3%2=1  
//3/2=1  0001
//1%2=1
//1/2=0

int count_one(unsigned int n)//形参必须为unsigned int,把负数转换成unsigned int
{
	int count = 0;
	while (n)
	{
		if (n % 2 == 1)
			count++;
		n /= 2;
	}
	return count;
}
int main()
{
	int num = 0;
	scanf("%d",&num);
	int ret = count_one(num);
	printf("%d\n",ret);

	return 0;
}

解法2

让二进制的每一位和1相与(&),结果若为1,则该位为1,否则为0

int count_one(int n)
{
	int i = 0;
	int count = 0;
	for (i = 0; i < 32; i++)
	{
		if ((n >> i) & 1 == 1)//不改变n
		{
			count++;
		}
	}
	return count;
}
int main()
{
	int num = 0;
	scanf("%d",&num);
	int ret = count_one(num);
	printf("%d\n",ret);

	return 0;
}

解法3(最经典)

n = n&(n-1)

n=15

n   =1111

n-1=1110

n   =1110

n-1=1101

n   =1100

n-1=1011

n  = 1000

...

直到n=0,计算相与的次数

int count_one(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(num);
	printf("%d\n",ret);

	return 0;
}

你可能感兴趣的:(c语言,算法,开发语言)