Problem Statement

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Note:

Example 1:

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string11111111111111111111111111111101 has a total of thirty one '1' bits.

Constraints:

Problem Link

Number of 1 Bits - LeetCode

Approach

The way to think about it is that for any number, lets say 4 (0100), 1 subtracted by that number will always set all the LSB's below the lowest set bit and clear the lowest set bit (ie. 3 = 0011). So when you do n&(n-1) you know that the last set bit is going to get cleared because 0100 & 0011 is 0, so you keep clearing and increment count along the way until all the bits are cleared (you clear them from the lowest set bit to the highest).

Code

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