題目
請實現一個函數,輸入一個整數,輸出該數二進制表示中 1 的個數。例如,把 9 表示成二進制是 1001,有 2 位是 1。因此,如果輸入 9,則該函數輸出 2。
題目來源:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/
思路
代碼
class Solution {
public:
int hammingWeight(uint32_t n) {
int ret = 0;
for (int i = 0; i < 32; i ++) {
if (n & (1 << i)) {
ret ++;
}
}
return ret;
}
};