← DSA
EASY

Number of 1 Bits

PracticeNeetCode ↗LeetCode ↗

Given a positive integer n, return the number of set bits (1s) in its binary representation — the Hamming weight.

Example

Input n = 11 (binary 1011)
Output 3

Key Pointers

Step-by-Step Analysis

  1. Initialize count = 0.
  2. While n is nonzero: set n = n & (n - 1), clearing its lowest 1-bit, and increment count.
  3. Once n reaches 0, every set bit has been cleared and counted.
  4. Return count.

Complexity

Time: O(k) where k is the number of set bits — Space: O(1)

Code

def hammingWeight(n: int) -> int:
    count = 0
    while n:
        n &= n - 1
        count += 1
    return count

Code Explanation

How the solution above works, piece by piece.

  1. n - 1 flips the lowest set bit to 0 and every bit below it to 1.
  2. So n &= n - 1 clears exactly the lowest set bit.
  3. Count how many times that can happen before n becomes 0: that's the number of 1 bits.
  4. The loop runs once per set bit, not once per bit position.

Visual Walkthrough

Running it on n = 11 (binary 1011):

trace1011#11011 & 1010 = 10101010#21010 & 1001 = 10001000#31000 & 0111 = 0000 → count 3
11 is 1011 in binary. Each step clears the lowest 1 (red): 1011 → 1010 → 1000 → 0000. Three steps, so three 1 bits.
bit cleared

Video Explanation

NeetCode — LeetCode 191