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.
目的是判断一个数字的二进制中有点多少个1,
我们可以通过数字的二进制右移的性质进行判断,判断数字的最后一位是不是1,如果是则进行相加:
直到数字为0
class Solution {
public:
int hammingWeight(uint32_t n) {
int result=0;
int move;
while(n!=0){
move=n& 0x1;
result=result+move;
n=n>>1;
}
return result;
}
};
n = 0x110100 n-1 = 0x110011 n&(n - 1) = 0x110000
n = 0x110000 n-1 = 0x101111 n&(n - 1) = 0x100000
n = 0x100000 n-1 = 0x011111 n&(n - 1) = 0x0
看到这里已经得到了一种新的解法,n中本来有3个1,按照此种思路只需要循环3此即可求出最终结果,
n&(n-1)用于求解n中1的个数,每次n&(n-1)就是消去数字末尾中的1,,通过循环我们可以直到数字中有多少个二进制1,、
class Solution {
public:
int hammingWeight(uint32_t n) {
int result=0;
while(n!=0){
n=n&(n-1);
result++;
}
return result;
}
};