Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Number of 1 Bits Explained

Problem Statement

Given a 32-bit unsigned integer n, count the number of 1 bits in its binary representation, also known as the Hamming weight. For example, the number 11 (binary: 1011) has three 1 bits. This problem tests your ability to manipulate bits efficiently, typically using bitwise AND and shift operations to inspect each bit.

Example

Input: n = 11

Output: 3

Explanation: The binary representation of 11 is 1011, which contains three 1 bits.

Code

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

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.hammingWeight(11)); // 3
    }
}
            
def hamming_weight(n):
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count

# Example usage
print(hamming_weight(11))  # 3
            
function hammingWeight(n) {
    let count = 0;
    while (n) {
        count += n & 1;
        n >>>= 1;
    }
    return count;
}

// Example usage
console.log(hammingWeight(11)); // 3
            

Explanation

  • Initialize a counter count to track the number of 1 bits.
  • While n is non-zero, extract the least significant bit using n & 1.
  • Add the bit (0 or 1) to count.
  • Right-shift n by 1 to process the next bit.
  • Return the total count when all bits are processed.

Note

The time complexity is O(1) since we process at most 32 bits for a 32-bit integer. Use unsigned right shift (>>>) in Java and JavaScript to handle unsigned integers correctly. An alternative is to use n & (n - 1) to clear the rightmost 1 bit each iteration.