原题链接:https://leetcode.com/problems/number-of-1-bits/
递归解法:
class Solution {
public:
int hammingWeight(uint32_t n) {
if(n == 0)
return 0;
if(n % 2 == 1)
return hammingWeight(n/2)+1;
else
return hammingWeight(n/2);
}
};
迭代解法:
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
while(n)
{
if(n % 2 == 1)
cnt++;
n = n / 2;
}
return cnt;
}
};