美文网首页Leetcode
Leetcode 191. Number of 1 Bits

Leetcode 191. Number of 1 Bits

作者: SnailTyan | 来源:发表于2018-09-03 18:54 被阅读8次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Number of 1 Bits

2. Solution

  • Version 1
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        int m = 1;
        while(n) {
            count += (m & n);
            n >>= 1; 
        }
        return count;
    }
};
  • Version 2
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        int m = 1;
        while(n) {
            count++;
            n &= (n - 1); 
        }
        return count;
    }
};

Reference

  1. https://leetcode.com/problems/number-of-1-bits/description/

相关文章

网友评论

    本文标题:Leetcode 191. Number of 1 Bits

    本文链接:https://www.haomeiwen.com/subject/bhpiwftx.html