Leetcode

Leetcode 191. Number of 1 Bits

2018-09-03  本文已影响8人  SnailTyan

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

1. Description

Number of 1 Bits

2. Solution

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        int m = 1;
        while(n) {
            count += (m & n);
            n >>= 1; 
        }
        return count;
    }
};
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/
上一篇下一篇

猜你喜欢

热点阅读