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.
nis 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?
- 1 <= n <= 2³¹ - 1
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.
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.
Approach
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?
Two ways to solve it
Replace n with n & (n − 1) until it is 0.
- Rounds: one per 1 bit, at most 31.
- No shifts: nothing to get wrong about signed shifts.
The usual interview answer.
Add n & 1, then shift n right by one, until it is 0.
- Rounds: one per binary digit, so 128 takes eight.
- Obvious: the first idea most people write.
Fine, just slower on sparse numbers.
Both are O(1) for a 31-bit number. Clearing the lowest 1 wins because it skips the 0s and does one round per 1 bit. The steps, code and live demo follow that method; the bit-by-bit loop comes after the demo.
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.
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.
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.
Code in Python, C++ and Java
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.
Common pitfalls
Looping on the power-of-two test
while n & (n - 1):
n &= n - 1
count += 1while n:
n &= n - 1
count += 1n & (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
for _ in range(32):
n &= n - 1
count += 1while n:
n &= n - 1
count += 1Once 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.
Edge cases
All 31 bits are 1, so the loop runs its maximum of 31 rounds and returns 31.
Complexity
n, at most 31 here, so the time is also O(1) for this input range. Only count and n are stored.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.