My 10ms C++ solution using bit operation.


  • 12
    V
    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int ans = 0;
            while (n) {
                n &= (n-1);
                ans++;
            }
            return ans;
        }
    };

  • 0
    W

    more concise:)

    int hammingWeight(uint32_t n) {
        int num = 0;
        for (; n > 0; ++num, n &= (n-1));
        return num;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.