【题目】
请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
来源:leetcode
链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/
【示例1】
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’
【注意】
本题与主站 191 题相同:https://leetcode-cn.com/problems/number-of-1-bits/
【知识点】
uint32_t
请参考
https://www.cnblogs.com/ace9/archive/2011/04/29/2032903.html
【代码】
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt=0;
while(n){
if(n%2)
cnt++;
n/=2;
}
return cnt;
}
};