191. Number of 1 Bits
来源:互联网 发布:c 浏览器源码 编辑:程序博客网 时间:2024/05/16 11:45
题目
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 00000000000000000000000000001011, so the function should return 3.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
分析:
//0x表示此数为16进制表示方法
// 0x1表示为2进制就是0001
// <<是移位操作 表示左移,>>表示右移
比较简单,只需要让n和1求与,如果个位为1,则count+1;然后向右移位即可。最后得到count的值即为1的个数.但是问题在于这样计算会出现报错,因为输入为: 2147483648 (10000000000000000000000000000000),但这个输入超过了整型的上限。当输入为2147483648时,会将这个数字判断位-1,而右移符号>>在计算时会保持数字的符号位,即正数右移高位补0,负数右移高位补1。使用这种规则进行右移,会导致数字在右移过程中被不断补1,这样循环永远无法停止!
因此采用n&(n-1)的方式,每执行一次x = x&(x-1),会将x用二进制表示时最右边的一个1变为0,因为x-1将会将该位(x用二进制表示时最右边的一个1)变为0。
因此
源码
这个源码会报错//JavaScript:/** * @param {number} n - a positive integer * @return {number} */var hammingWeight = function(n) { var count=0; while(n>0){ if(n & 0x1) { count++; } n=n>>1; } return count;};//c++:class Solution {public: int hammingWeight(uint32_t n) { int count=0; while(n>0){ count=count+n&1; n>>1; } return count; }};
正确的:
C++
class Solution {public: int hammingWeight(uint32_t n) { int count=0; while(n!=0){ n=n&(n-1); count++; } return count; }};
- 191.Number of 1 Bits
- 191.Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191.Number of 1 Bits
- .Net MSMQ
- layoutSubviews何时调用的问题
- JavaScript学习目录
- iOS APP 逆向安全杂谈之三
- cmstop框架中顶级类总结
- 191. Number of 1 Bits
- 设计模式之观察者模式(关于OC中的KVO\KVC\NSNotification)
- Android学习笔记之AndroidManifest.xml文件解析
- pip安装lxml出错的问题解决
- AndroidAPP更新升级完整实现Demo(搭建本地服务器) .
- 同一个Activity中不同Fragment的数据传递
- Android 学习 2016.03.08
- java 遍历map 方法 集合 五种的方法
- kibana