LeetCode #191 Easy

Number of 1 Bits

Number of 1 Bits is LeetCode 191 (Easy). Given a positive integer n, return how many 1s appear in its binary form. This count is also called the Hamming weight of n.

  • n is between 1 and 2³¹ − 1, so it is never negative and has at most 31 binary digits.
  • Follow-up: if the function is called many times, how would you speed it up?
Constraints
  • 1 <= n <= 2³¹ - 1
bit-manipulation
Open on LeetCode ↗
02

Intuition

Subtracting 1 from n only touches the lowest 1 bit and the 0s below it: that 1 becomes 0, and each of those 0s becomes 1. Every bit above stays the same.

So n & (n − 1) keeps the bits above and clears everything from the lowest 1 down. Each AND removes exactly one 1 bit. Repeat until n is 0 and count the rounds. This is Brian Kernighan's algorithm, and it runs once per 1 bit rather than once per bit position: 128 (binary 10000000) takes one round, not eight.

How to spot this pattern

Any question about how many bits are set, or about the lowest set bit, points to n & (n − 1). The same AND is behind the power-of-two test, which checks whether one round already reaches 0.

03

Approach

Try it first

Before reading on, write 12 and 11 in binary, one above the other, and AND them. Which bit of 12 disappeared, and what would happen if you kept going until the number is 0?

1

Start the count at 0

count will go up by one each time a 1 bit is removed, so it starts at 0. The constraints promise n >= 1, so at least one round will run.

2

Clear the lowest 1 bit

While n is not 0, set n = n & (n - 1) and add 1 to count. Subtracting 1 flips the lowest 1 and the 0s under it, so the AND wipes that one bit and leaves every higher bit alone.

3

Return the count when n reaches 0

Each round removed exactly one 1 bit and nothing else, so once none are left, count equals the number of 1s the input had. For n < 2³¹ that is at most 31 rounds.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def hammingWeight(self, n: int) -> int:
▶3 count = 0
▶4 while n:
▶5 n &= n - 1
▶6 count += 1
▶7 return count
n = 11180412111 bits removed, by valuenone yetcount0start with 11 and a count of 0
n11binary 1011
count0
Write 11 in binary: 1011. The small numbers under the lamps are what each bit is worth. Each round of the loop will remove one lit lamp and add 1 to the count.
n = 1118041211flipped by n − 11 bits removed, by valuenone yetcount0n − 1 flips only the lowest 1 (worth 1)
n111011
n − 1101010
Subtracting 1 from 11 gives 10. Only the marked lamps change: the lowest 1 (worth 1) turns off. Every lamp to the left of it is the same in both numbers, so the AND will keep exactly those.
n = 10180412011 bits removed, by value1count1AND keeps the bits above → 11 becomes 10, count 1
n101010
count1
1011 AND 1010 is 1010: the lamp worth 1 is now off and nothing else moved. One 1 bit is gone, so the count goes up to 1. n is not 0 yet, so loop again.
n = 1018041201flipped by n − 11 bits removed, by value1count1n − 1 flips the lowest 1 (worth 2) and 1 zero
n101010
n − 191001
Subtracting 1 from 10 gives 9. Only the marked lamps change: the lowest 1 (worth 2) turns off and the 1 zero under it turn on. Every lamp to the left of it is the same in both numbers, so the AND will keep exactly those.
n = 8180402011 bits removed, by value1+2count2AND keeps the bits above → 10 becomes 8, count 2
n81000
count2
1010 AND 1001 is 1000: the lamp worth 2 is now off and nothing else moved. One 1 bit is gone, so the count goes up to 2. n is not 0 yet, so loop again.
n = 818040201flipped by n − 11 bits removed, by value1+2count2n − 1 flips the lowest 1 (worth 8) and 3 zeros
n81000
n − 17111
Subtracting 1 from 8 gives 7. Only the marked lamps change: the lowest 1 (worth 8) turns off and the 3 zeros under it turn on. Every lamp to the left of it is the same in both numbers, so the AND will keep exactly those.
n = 0080402011 bits removed, by value1+2+8count3AND keeps the bits above → 8 becomes 0, count 3
n00
count3
1000 AND 111 is 0: the lamp worth 8 is now off and nothing else moved. One 1 bit is gone, so the count goes up to 3.
n = 0080402011 bits removed, by value1+2+8=11count3n is 0 → answer: 3
answer3
rounds3one per 1 bit
Every lamp is off, so the loop stops after 3 rounds, one per 1 bit; checking every bit position would take 4. As a check, the removed values add back up to 11.
05

Check each bit and shift

Look at the lowest bit with n & 1, add it to the count, and shift n right to bring the next bit down. The loop ends when no 1s are left above, so it runs once per binary digit of n.

▶1class Solution:
▶2 def hammingWeight(self, n: int) -> int:
▶3 count = 0
▶4 while n:
▶5 count += n & 1
▶6 n >>= 1
▶7 return count
06

Common pitfalls

Looping on the power-of-two test

✗ Wrong
while n & (n - 1):
    n &= n - 1
    count += 1
✓ Right
while n:
    n &= n - 1
    count += 1

n & (n - 1) == 0 is the check for a power of two, so this loop stops while one 1 bit is still left. For n = 11 it returns 2 instead of 3, and for n = 128 it returns 0.

Counting the rounds of a fixed loop

✗ Wrong
for _ in range(32):
    n &= n - 1
    count += 1
✓ Right
while n:
    n &= n - 1
    count += 1

Once n is 0, n & (n - 1) stays 0, but the loop still adds 1 every time. The answer is always 32. The trick needs the loop to stop at 0.

07

Edge cases

n = 2³¹ − 1 = 2147483647

All 31 bits are 1, so the loop runs its maximum of 31 rounds and returns 31.

08

Complexity

Time
O(k)
Space
O(1)
k is the number of 1 bits in n, at most 31 here, so the time is also O(1) for this input range. Only count and n are stored.
09

Number of 1 Bits FAQ

How do you answer the follow-up for many calls?

Precompute a table of 256 counts, one for every byte value, using table[i] = table[i >> 1] + (i & 1). Then each call is four lookups: n & 255, (n >> 8) & 255, (n >> 16) & 255 and n >> 24, added together. The table is built once and costs 256 small numbers.

Why do some solutions use >>> or uint32_t?

An older version of the problem passed a 32-bit unsigned value, which arrives in Java as a negative int when its top bit is set. Shifting a negative int with >> copies the sign bit in, so a shift loop never reaches 0; >>> shifts in 0s. Today's inputs are positive, and the n & (n − 1) loop needs no shift at all.

Is there a built-in?

Yes: n.bit_count() in Python 3.10+, Integer.bitCount(n) in Java and __builtin_popcount(n) in C++. They are fine in real code; interviewers usually ask for the loop.