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.4
题目很简单,直接循环与十六进制0X1进行&运算即可,需要注意的是累计加法的时候要添加括号。
class Solution {
public:
int hammingWeight(uint32_t n) {
int bitnum=0;
while(n!=0)
{
bitnum=bitnum+(n&0x1); //或者 bitnum+=n&0x1, 如果写成 bitnum=bitnum+n&0x1 是错的,这也是唯一需要注意的地方。
n=n>>1;
}
return bitnum;
}
};