Number of 1 Bits

Easy

Topics
Bit Manipulation

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

Example 1

76543210n = 1100001011
The answer is simply how many cells hold a 1 — 3 here. The trick worth knowing is n & (n-1), which clears the lowest set bit, so the loop runs once per set bit rather than 32 times.
Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input:  n = 11
Output: 3
Explanation: 11 = 1011 in binary.

Example 2

76543210n = 12810000000
Input:  n = 128
Output: 1

Constraints

  • 0 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

The identity n & (n - 1) clears the lowest set bit. Repeatedly applying it counts exactly as many iterations as there are set bits.

Approach

  1. Initialize a counter to 0.
  2. While n is non-zero, do n &= n - 1 and increment the counter.
  3. Return the counter.

Walkthrough

n = 11 (1011)
1011 & 1010 = 1010  (count 1)
1010 & 1001 = 1000  (count 2)
1000 & 0111 = 0000  (count 3) -> answer 3

Complexity

  • Time — O(bits set): one iteration per set bit (at most 32).
  • Space — O(1): a single counter.

Common Pitfalls

  • Count the ones in the binary representation. Counting the character 1 in the decimal string is a different question entirely and returns 2 instead of 3 for 11.
  • n & (n - 1) clears the lowest set bit, so looping on that runs once per set bit rather than once per bit width. Worth naming as the answer when the interviewer asks for it without a built-in.

Full Solution — all languages

class Solution:
    def hammingWeight(self, n):
        return bin(n).count('1')
SensAI
Beta
Tap the mic to stop voice mode