博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
计算一个整数二进制中1的个数
阅读量:4513 次
发布时间:2019-06-08

本文共 1583 字,大约阅读时间需要 5 分钟。

这是来自牛客网关于一个二进制的运算

我的思路为每次和1 2 4 .....进行按位与运算就可得到二进制中1的个数

代码如下

1 /* 2  * *new coder ponint to offer 11 3  * find bit 1 num of a nunber  4  */ 5  6 #include 
7 #include
8 9 int find1num(int number)10 {11 int i = 1,count = 0;12 13 //while( number / i != 0 ) //if number is negtive we will count error14 15 while( i != 0 )16 {17 if( (number & i) != 0)18 {19 count++;20 } 21 22 i <<= 1; //i = i * 223 }24 25 return count;26 }27 28 int main()29 {30 31 int number;32 33 while(1)34 {35 scanf("%d",&number);36 37 int count = find1num(number);38 39 printf("num of bit 1 is : %d\n",count);40 }41 }

下面是另外一个大哥的思路,可以明显的减少循环的次数。思路为每次将整数和整数-1的数做与运算这样每次将整数最右边的1变成0,这样做的次数就是整数中含有1的个数,代码如下:

1 /* 2  * *new coder ponint to offer 11 3  * find bit 1 num of a nunber 4  * time best  5  */ 6  7 #include 
8 #include
9 10 int find1num(int number)11 {12 int count = 0;13 14 15 while( number != 0 )16 {17 count++;18 number = number & (number - 1); //every time do this will make the rightest 1 of number to 0 so we can do this opration the count 1 of number times19 }20 21 return count;22 }23 24 int main()25 {26 27 int number;28 29 while(1)30 {31 scanf("%d",&number);32 33 int count = find1num(number);34 35 printf("num of bit 1 is : %d\n",count);36 }37 }

 

转载于:https://www.cnblogs.com/daimadebanyungong/p/4917630.html

你可能感兴趣的文章
Discretized Streams, 离散化的流数据处理
查看>>
Spark源码分析 – SchedulerBackend
查看>>
python字符串处理
查看>>
live555学习笔记4-计划任务(TaskScheduler)深入探讨
查看>>
Python虚拟机函数机制之名字空间(二)
查看>>
线段树
查看>>
SharePoint2010联合搜索——Google、百度
查看>>
php静态
查看>>
python基础之文件操作
查看>>
在eclipse里头用checkstyle检查项目出现 File contains tab characters (this is the first instance)原因...
查看>>
个人github链接及git学习心得总结
查看>>
c++ 计算器 带括号 代码实现
查看>>
objective -c初写
查看>>
C#中如何设置窗体的默认按钮和取消按钮
查看>>
[Swift]LeetCode276. 粉刷栅栏 $ Paint Fence
查看>>
[Swift]LeetCode351. 安卓解锁模式 $ Android Unlock Patterns
查看>>
break语句和continue语句
查看>>
java代码中添加log4j日志
查看>>
Java学习不走弯路教程(19 对于Service的自动注入)
查看>>
[CSS3] :empty Selector
查看>>