当前位置:网站首页>C语言:求一个整数存储在内存中的二进制中1的个数
C语言:求一个整数存储在内存中的二进制中1的个数
2022-07-28 03:42:00 【高邮吴少】
int main()
{
//对于负数我们统计的是补码中有多少个1
//比如-1
//原:10000000 00000000 00000000 00000001
//反:11111111 11111111 11111111 11111110
//补:11111111 11111111 11111111 11111111
//-1存储在内存中二进制1的个数就是32
int a = 0;
printf("请输入你想测试的整数:");
scanf("%d", &a);
int tmp = a;
int count = 0;
if (a >= 0)
{
while (a)
{
if (a & 1) {
//可以判断出当前a最后一位是1还是0
count++;
}
a = a >> 1;
}
}
else
{
//负数右移,我这个编译器是算术右移(大多数编译器都是算术右移)
//算术右移就是,最右边数丢弃,左边补符号位,因为是负数也就是补1
//这里如果还用while(a)就会一直死循环下去,因为左边会一直补1
//但我们是知道整形是32位存储在内存里面的,我们循环32次即可
for (int i = 0;i < 32;i++)
{
if (a & 1) {
//可以判断出当前a最后一位是1还是0
count++;
}
a = a >> 1;
}
}
printf("%d存储在内存中二进制1的个数为%d", tmp,count);
return 0;
}
牛客网测试通过截图
相关题目链接:二进制中1的个数
边栏推荐
- 容器相关的概念
- [openvx] VX for basic use of objects_ pyramid
- After reading MySQL database advanced practice (SQL xiaoxuzhu)
- MySQL Basics (create, manage, add, delete, and modify tables)
- ASEMI整流桥GBPC5010,GBPC5010参数,GBPC5010大小
- 收藏|0 基础开源数据可视化平台 FlyFish 大屏开发指南
- 【OPENVX】对象基本使用之vx_matrix
- ES6 从入门到精通 # 08:扩展的对象的功能
- 95后阿里P7晒出工资单:真的是狠狠扎心了...
- After 95, Alibaba P7 published the payroll: it's really heartbreaking
猜你喜欢

Integrate SSM to realize search of addition, deletion, modification and query

Qt:QMessageBox消息框、自定义信号和槽

4-day excel practical training camp, 0.01 yuan special offer for only three days, 200 sets of learning kits

数据挖掘-01

2022 summary of the latest Android handler related interview questions

高等数学(第七版)同济大学 习题3-4 个人解答(前8题)

沃尔沃:深入人心的“安全感” 究竟靠的是什么?

Volvo: what on earth does the deep-rooted "sense of security" rely on?

【5G NR】RRC Reject解析

ES6 from getting started to mastering 09: symbol type
随机推荐
After 95, Alibaba P7 published the payroll: it's really heartbreaking
2022-07-27: Xiao Hong got an array arr with a length of N. she is going to modify it only once. She can modify any number arr[i] in the array to a positive number not greater than P (the modified numb
最新版宝塔安装zip扩展,php -m 不显示的处理方法
pip-script.py‘ is not present Verifying transaction: failed
Weekly recommended short video: how to correctly understand the word "lean"?
Differences among BRD, MRD and PRD
Assembly method of golang Gorm query arbitrary fields
203. Remove linked list elements
695. 岛屿的最大面积
某宝模拟登录,减少二次验证的方法
Illustrated: detailed explanation of JVM memory layout
玩一玩WolframAlpha计算知识引擎
整合SSM实现增删改查搜索
【P4】解决本地文件修改与库文件间的冲突问题
Capacity expansion and reduction of RBD block storage device (VI)
Swift中的协议
动态规划——416. 分割等和子集
D2dengine edible tutorial (4) -- draw text
ASEMI整流桥GBPC3510在直流有刷电机中的妙用
8000字讲透OBSA原理与应用实践