Skip to content

Latest commit

 

History

History
34 lines (32 loc) · 561 Bytes

191. Number of 1 Bits.md

File metadata and controls

34 lines (32 loc) · 561 Bytes

题目

[191. Number of 1 Bits])(https://leetcode-cn.com/problems/number-of-1-bits/)

思路

4ms 85.72% 思路一:逐位取出n,然后计数。

8ms 54.89% 思路二:使用bitset库

代码

思路一

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int ans=0,k=32;
        while(k-->0){
            if(n&1)ans++;
            n=n>>1;
        }
        return ans;
    }
};

思路二

class Solution {
public:
    int hammingWeight(uint32_t n) {
        bitset<32> b(n);
        return b.count();
    }
};