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

方法1:

#include<stdio.h>
int count(int n)
{
	int count=0;
	while (n)
	{
		n = n & (n - 1);
		count++;
	}
	return count;
}
int main()
{
	int num;
	scanf("%d", &num);
	int n = count(num);
	printf("%d", n);
	return 0;
}

方法2:

#include<stdio.h>
int count(int n)
{
	int i,count=0;
	for (i = 0; i < 32; i++)
	{
		if (((n >> i) & 1) == 1)
		{
			count++;

		}
	}
	return count;
}
int main()
{
	int num;
	scanf("%d", &num);
	int n = count(num);
	printf("%d", n);
	return 0;
}

方法3:

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

相关推荐

  1. C语言 三种方法求一个整数二进制1个数

    2024-07-13 02:06:08       51 阅读
  2. 华为OD机考题(HJ62 查找输入整数二进制1个数)

    2024-07-13 02:06:08       20 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-13 02:06:08       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-13 02:06:08       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-13 02:06:08       58 阅读
  4. Python语言-面向对象

    2024-07-13 02:06:08       69 阅读

热门阅读

  1. C#中的泛型

    2024-07-13 02:06:08       18 阅读
  2. 力扣636.函数的独占时间

    2024-07-13 02:06:08       19 阅读
  3. day19打卡

    2024-07-13 02:06:08       16 阅读
  4. 【qml学习笔记】在qml中连接信号与槽

    2024-07-13 02:06:08       22 阅读
  5. 【第20章】MyBatis-Plus逻辑删除支持

    2024-07-13 02:06:08       13 阅读
  6. AI agents 印象

    2024-07-13 02:06:08       18 阅读
  7. Kafka 面试题精选

    2024-07-13 02:06:08       23 阅读
  8. gpt讲 Observable 对象

    2024-07-13 02:06:08       21 阅读