Number of 1 Bits
来源:互联网 发布:简单java单线程程序 编辑:程序博客网 时间:2024/06/15 16:20
解法来源剑指offer,题10
1.可能引起死循环的解法
int NumberOf1(int n){ int count = 0; while(n) { if(n&1) count++; n = n >> 1; } return count;}
若为负数如0x80000000移位为0xC0000000,最终变为0xFFFFFFFF陷入死循环。
2.better
int NumberOf1(int n){ int count = 0; unsigned int flag = 1; while(flag) { if(n & flag) count++; flag = flag << 1; } return count;<pre name="code" class="cpp"> }
3.best
int NumberOf1(int n){ int count = 0; while(n) { count++; n = (n - 1) & n; } return count;}
0 0
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- MySql创建本地用户和远程用户 并赋予权限
- C++ Primer Plus第六版 第十一章 编程练习答案
- java 抽象类和接口
- PAT(甲级)1056
- Perl 类继承简单讲解
- Number of 1 Bits
- PAT(甲级)1057
- 283:Move Zeroes
- 树的深度优先与广度优先遍历
- Java反射通过class获取父类泛型类型
- log4j配置
- JMS学习
- C++ string类型的split字符串分割函数
- 线段树查询