191. Number of 1 Bits
2016-07-26 16:34
253 查看
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming
weight).
For example, the 32-bit integer ’11' has binary representation
so the function should return 3.
方法1,直接数
方法2
https://discuss.leetcode.com/topic/9915/short-code-of-c-o-m-by-time-m-is-the-count-of-1-s-and-another-several-method-of-o-1-time
Each time of "n &= n - 1", we delete one '1' from n. (rightest one)
方法3
来自JDK1.5函数Integer.bitCount()源码
解释摘自http://bbs.csdn.net/topics/310240176
(以8bit为例):使用0x55作位运算也就是将X的位两两累加,如 11 01 10 11 两两累中后 得到 10 01 01 10,
因为1+1=10 0+1=01 1+0=01 1+1=10 ,所以每二位一组标示X的二位的1的个数。
然后,以0x33对结果做位运算,为什么是0x33呢,因为结果是两位的,所以 是将其两位一组两两相加
得到 0011 0011 这一结果是四位一组的,每四位标示X的四位中的1的个数,
再使用0x0f做位运算,可想而知,得到的是八位组标示的X的每八位中的1的个数。因为X只有八位,所以到此结束
结果为 0011+0011=0000 0110 ,即6个1
更多位数以此类推
weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011,
so the function should return 3.
方法1,直接数
public int hammingWeight(int n) { int cnt=0; for(int i=0;i<32;i++) { if((n&0x1)==1) cnt++; n>>>=1; } return cnt; }
方法2
https://discuss.leetcode.com/topic/9915/short-code-of-c-o-m-by-time-m-is-the-count-of-1-s-and-another-several-method-of-o-1-time
Each time of "n &= n - 1", we delete one '1' from n. (rightest one)
O(m) by time, m is the count of
1's,
int hammingWeight(uint32_t n) { int res = 0; while(n) { n &= n - 1; ++ res; } return res; }
方法3
来自JDK1.5函数Integer.bitCount()源码
解释摘自http://bbs.csdn.net/topics/310240176
(以8bit为例):使用0x55作位运算也就是将X的位两两累加,如 11 01 10 11 两两累中后 得到 10 01 01 10,
因为1+1=10 0+1=01 1+0=01 1+1=10 ,所以每二位一组标示X的二位的1的个数。
然后,以0x33对结果做位运算,为什么是0x33呢,因为结果是两位的,所以 是将其两位一组两两相加
得到 0011 0011 这一结果是四位一组的,每四位标示X的四位中的1的个数,
再使用0x0f做位运算,可想而知,得到的是八位组标示的X的每八位中的1的个数。因为X只有八位,所以到此结束
结果为 0011+0011=0000 0110 ,即6个1
更多位数以此类推
public static int bitCount(int i) { // HD, Figure 5-2 i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; }
相关文章推荐
- MFC带自动水平滚动条ListBox
- 玩转HTML5移动页面——动效篇
- java泛型
- base64上传图片
- Spark1.6.0 on Hadoop-2.6.3 安装配置
- 华为上机:实现两个合法时间相加
- [kafka] 004_kafka_安装运行
- RedHat(小红帽)下 yum用不了的解决办法
- Oozie Hive action XML Schema版本冲突
- 使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据) (3)
- UIDatePicker
- XML DOM完全参考手册(一)DOM与节点
- CoCreateInstance(转)
- swift - UIScrollView 的使用
- iOS流布局UICollectionView系列三——使用FlowLayout进行更灵活布局
- 我是如何构建一个持续发展的项目
- Sql -- 练习1 查询每科成绩前两名的学生信息
- Android开发SDK过程中的一些事
- EJS 模板快速入门
- JAVA设计模式之单例模式