📝 Problem Details

input integer n n is a positive integer write a function that returns the number of set bits in its binary representation AKA Hamming Weight

💡 Explanation of Solution

Use bit-masking:
- iterate through each bit position (32 times for a 32-bit integer)
- check if the i-th bit is set using (n >> 1) & 1
- count how many bits are 1

⌛ Complexity Analysis

Time Complexity: O(1)
O(32) = O(1), since it's a constant number of iterations

Space Complexity: O(1)

💻 Implementation of Solution

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