求二进制中1的个数

方法1:

#define _CRT_SECURE_NO_WARNINGS 1
#include
#include

int BinaryNumOf1(int num)
{
	int count = 0;
	while (num)
	{
		if (num & 1)
		{
			count++;
		}
		num = num >> 1;
	}
	return count;
}

int main()
{
	int num = 10;
	int ret = BinaryNumOf1(num);
	printf("%d\n", ret);
	system("pause");
	return 0;
}

方法2:

#define _CRT_SECURE_NO_WARNINGS 1
#include
#include

int BinaryNumOf1(int num)
{
	int count = 0;
	while (num)
	{
		count++;
		num = num & (num - 1);
	}
	return count;
}

int main()
{
	int num = -10;
	int ret = BinaryNumOf1(num);
	printf("%d\n", ret);
	system("pause");
	return 0;
}

方法3:

int Function(unsigned int n) {	
		n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
		n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
		n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f);
		n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff);
		n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff);
		return n;
}

你可能感兴趣的:(C语言,c)