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的个数。
方法一:将待处理数 n 进行右移,依次与1与
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n>0) {
count += n&1;
n >>=1;
}
return count;
}
};
方法二:将1左移一次与待处理数 n 与
class Solution {
public:
int hammingWeight(uint32_t n) {
int pos=1,count=0;
for(int i=0;i<32;++i){
if(n&pos)
++count;
pos = pos<<1;
}
return count;
}
};