KatInterview

191. Number of 1 Bits

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to count the number of '1's in the binary representation of a given positive integer n. This count is also known as the Hamming weight. For example, the binary representation of 11 is 1011, which has three '1's, so its Hamming weight is 3.

Solution

Number of 1 Bits in Python

class Solution:
    def hammingWeight(self, n: int) -> int:
        count = 0
        # The loop runs until all set bits are cleared and n becomes 0.
        while n != 0:
            # This is Brian Kernighan's algorithm.
            # The operation n & (n - 1) flips the least significant set bit (rightmost '1') to '0'.
            # We increment a counter for each time we do this.
            # The loop will run k times, where k is the number of set bits.
            n = n & (n - 1)
            count += 1
        return count

Number of 1 Bits in Java

class Solution {
    public int hammingWeight(int n) {
        int count = 0;
        // The loop continues as long as n is not zero. 
        // This condition works for both positive and negative numbers (in two's complement).
        while (n != 0) {
            // This bit manipulation trick (Brian Kernighan's algorithm) clears the rightmost '1' bit.
            // For example, if n = 11 (binary 1011), n-1 is 10 (1010).
            // n & (n-1) becomes 1011 & 1010 = 1010 (decimal 10).
            // The loop iterates exactly as many times as there are set bits.
            n = n & (n - 1);
            count++;
        }
        return count;
    }
}

Number of 1 Bits in C++

class Solution {
public:
    int hammingWeight(int n) {
        int count = 0;
        // Although the problem specifies n is a positive integer, it's a good practice
        // in bit manipulation problems to use unsigned types to avoid issues with
        // the sign bit and signed integer overflow. We cast n to unsigned int.
        unsigned int u_n = n;

        // The loop continues as long as there are set bits in u_n.
        while (u_n != 0) {
            // The operation u_n & (u_n - 1) clears the least significant set bit (the rightmost '1').
            // For example, if u_n = 12 (binary 1100), u_n - 1 is 11 (binary 1011).
            // u_n & (u_n - 1) results in 1000 (decimal 8).
            // By doing this repeatedly, we turn off one '1' bit at a time.
            u_n = u_n & (u_n - 1);
            // We increment the count for each '1' bit we turn off.
            count++;
        }
        return count;
    }
};

Number of 1 Bits in TypeScript

function hammingWeight(n: number): number {
    let count = 0;
    // In TypeScript/JavaScript, bitwise operations are performed on 32-bit signed integers.
    // The loop condition `n !== 0` works correctly for all 32-bit patterns.
    while (n !== 0) {
        // The expression n & (n - 1) unsets the rightmost set bit.
        // For example: 12 (1100) & 11 (1011) -> 8 (1000).
        // The number of times we can do this before n becomes 0 is the number of set bits.
        n = n & (n - 1);
        count++;
    }
    return count;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.