LeetCode191. 位1的个数

循环,逐位判断每一位是不是1。

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res = 0;
        for(int i = 0; i < 32; ++i) {
            res += (n >> i & 1) == 1 ? 1 : 0;
        }
        return res;
    }
};
posted @ 2020-08-04 15:48  machine_gun_lin  阅读(41)  评论(0)    收藏  举报