题目
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;
}
};