[leetcode]191. Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Example 1:

Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011 

分析:

返回一个无符号整数二进制中位1的个数。依次按位与1,若结果为1,则个数num+1,直至32位全部比较完即可。

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

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/84848291
今日推荐