0
点赞
收藏
分享

微信扫一扫

【C语言小题】统计二进制中1的个数

艾米吖 2022-01-27 阅读 80

统计二进制中1的个数

输入一个整数 n ,输出该数32位二进制表示中1的个数。其中负数用补码表示。

比如: 15 0000 1111 4 个 1

数据范围:- 2^(31) <=  n  <= 2^(31) - 1

即范围为:-2147483648 <= n <= 2147483647

方法一(巧妙)

解题思路

如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。

#include <stdio.h>

int count_number_of_1(int n)
{
	int count = 0;
	while (n)
	{
		n = n & (n - 1);
		count++;
	}
	return count;
}

int main()
{
	int n = 15;
	int ret = count_number_of_1(n);
	printf("%d\n", ret);
	return 0;
}

 方法二

#include <stdio.h>

int count_number_of_1(int n)
{
	int c = 0;
	int i = 0;
	for (i = 0; i < 32; i++)
	{
		if ((n & 1) == 1)
		{
			c++;
		}
		n >>= 1;
	}
	return c;
}

int main()
{
	int n = 15;
	int ret = count_number_of_1(n);
	printf("%d\n", ret);
	return 0;
}

方法三(效率一般)

使用unsigned int 接收传参,忽略判断正负数符号位的影响。

#include <stdio.h>

int count_number_of_1(unsigned int n)
{
	int c = 0;
	while (n)
	{
		if (n % 2 == 1)
		{
			c++;
		}
		n /= 2;
	}
	return c;
}

int main()
{
	int n = 15;//n放在内存中的补码的2进制中1的个数
	int ret = count_number_of_1(n);
	printf("%d\n", ret);
	return 0;
}

举报

相关推荐

0 条评论