欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【leetcode】191. Number of 1 Bits

程序员文章站 2024-03-11 22:07:01
...

题目:
Write a function that takes an unsigned integer and return the number of ‘1’ bits it has (also known as the Hamming weight).


思路:
利用mask挨个比较每一位就好了。


代码实现:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        uint32_t mask = 1;
        
        int count = 0;
        while (mask){
            if (n & mask){
                ++count;
            }
            
            mask <<= 1;
        }
        
        return count;
    }
};

【leetcode】191. Number of 1 Bits