当前位置:网站首页>C语言 ——求一个整数存储在内存中的二进制中的1的个数
C语言 ——求一个整数存储在内存中的二进制中的1的个数
2022-07-20 18:17:00 【numb and dying】
一、问题的描述
求一个整数存储在内存中的二进制中的1的个数。
举例:
8 二进制 为 1000 1 的个数为 1
7 二进制 为 0111 1 的个数为 3
二、方法一
缺点: 不能计算负数二进制中的1的个数
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main() {
int n = 0;
int count = 0;
printf("请输入一个整数: ");
scanf("%d", &n);
while (n != 0) {
if (n % 2 == 1) {
count++;
}
n /= 2;
}
printf("这个整数中 1 的个数为: %d\n", count);
return 0;
}
三、方法二
#include <stdio.h>
int main() {
int n = 0;
int count = 0;
printf("请输入一个整数:");
scanf("%d", &n);
for (int i = 0; i < 32; i++) {
if (1 == ((n >> i) & 1)) {
count++;
}
}
printf("你输入的整数有 %d 个 0 !!\n", count);
return 0;
}
四、方法三
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main() {
int n = 0;
int count = 0;
printf("请输入一个整数: ");
scanf("%d", &n);
while (n)
{
n = n & (n - 1);
printf("%d\n", n);
count++;
}
printf("这个整数的二进制中 1 的个数有 %d 个\n", count);
return 0;
}
边栏推荐
猜你喜欢
J9 says why digital science popularization will never die out
用Calendar中的add()方法对时间加减,获取时间范围,读取动态数据字典。
12.2包 和导入包
小红书关键词搜索商品列表API接口(商品详情页API接口)
12.2 package and import package
从一线开发到技术总监,你就差一个赶鸭子上架
[translation] in depth understanding of modern web browsers (4)
Pr视频剪辑师如何选笔记本?华硕灵耀Pro16 2022带你玩转内容创作
[format string] the principle and utilization of format string vulnerability
小红书商城整店商品API接口(店铺所有商品接口)
随机推荐
rogabet note 1.1
【盲盒APP商城系统】在线拆盒后的功能介绍
[译]深入了解现代web浏览器(四)
华为云数据治理生产线DataArts,让“数据‘慧’说话”
17 多态
二分查找
绘图库Matplotlib风格和样式
11.3 construction method
The regular expression gets the content between the two identities
感谢华为分享开发者计划
12 static and static initialization parameter value transfer
用Calendar中的add()方法对时间加减,获取时间范围,读取动态数据字典。
使用 GCC 避免堆栈粉碎攻击
A generation of "Boya" masters passed away! Memory of Professor yangfujia, former president of Fudan University and academician of the Chinese Academy of Sciences
MaxCompute实例相关操作
Solve the problem of connection rejected: connect and unauthorized connection when connecting mqtt
Select the self built database through dedicated line /vpn gateway / intelligent access gateway, and what should be paid attention to when filling in VPC ID?
set集合中的唯一性和排序问题
从一线开发到技术总监,你就差一个赶鸭子上架
【C语言】动态内存管理 - malloc等函数详解