LeetCode. 位1的个数

题目要求:

编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

示例:

输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。

代码:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        for(int i = 0; i < 32; i++) {
            if(n & 1 == 1) {
                count += 1;
            }
            n = n >> 1;
        }
        return count;
    }
};

分析:

采用位运算,以及数的移位来做。

posted @ 2019-10-15 23:07  Howardwang  阅读(118)  评论(0编辑  收藏  举报