Number of 1 Bits solution explained
The Number of 1 Bits solution that interviewers like best repeats one step: replace n with n & (n - 1), which erases the lowest 1 bit, and count how many times you can do it before n reaches zero. That loop runs once per set bit instead of once per bit position, uses O(1) memory, and is at most 32 iterations for a 32-bit input.
By Evin JohnPublished 7 min read
The problem in plain words
You are handed one 32-bit integer. Write it in binary and count the positions that hold a 1. The input is usually described as unsigned, but in languages without an unsigned type the same pattern may arrive as a negative number, so ask how it will be passed in.
| Input | Binary | Count |
|---|---|---|
| 88 | 1011000 | 3 |
| 0 | 0 | 0 |
| 2147483648 (2^31) | 1 followed by 31 zeros | 1 |
| 4294967295 (2^32 - 1) | 32 ones | 32 |
| -1 in a signed 32-bit language | the same 32 ones | 32 |
Why interviewers ask it
It is a short warm-up that tells the interviewer whether you are comfortable below the level of ordinary arithmetic. The first version is easy; the conversation that follows is where the signal is. Can you explain what n - 1 does to the binary pattern? Do you know that right-shifting a negative number in some languages copies the sign bit forever? It also shows up in embedded, systems and graphics interviews, where bit masks are part of daily work.
Follow-up questions
- Call it millions of times. Use a lookup table of counts for every 8-bit value and add four table reads, or the parallel counting trick shown below.
- Counts for every number from 0 to n. Reuse earlier answers instead of counting each one from scratch; that is the Counting Bits problem.
- Is the number a power of two? It has exactly one 1 bit, so n > 0 and (n & (n - 1)) == 0.
- Hamming distance between two numbers. Count the ones in a ^ b.
- Built-ins. Python 3.10 and later has
int.bit_count(), C++20 hasstd::popcount, and many compilers expose a popcount intrinsic. Mention them, then write the loop anyway.
A first answer: check every position
Look at the lowest bit with n & 1, add it to a counter, shift n right by one, and do that 32 times. It is correct and already O(1) for a fixed width, but it always does 32 steps, even for a value like 8 that has a single 1 bit. In Python, mask the input to 32 bits first so a negative number is read as its bit pattern instead of an endless run of ones.
def count_ones_by_shifting(n):
n &= 0xFFFFFFFF # read the input as 32 unsigned bits
count = 0
for _ in range(32):
count += n & 1
n >>= 1
return countThe better answer: erase one 1 bit at a time
Subtracting 1 from a number flips its lowest 1 bit to 0 and turns every 0 below it into a 1. Take 88, which is 1011000 in binary. 87 is 1010111. The lowest 1, in the eights place, became 0, and the three zeros under it became ones. AND the two together and everything from that position down becomes 0, while the higher bits are untouched: 1010000. One 1 bit has disappeared. Repeat until nothing is left, and the number of rounds is the answer.
def count_ones(n):
n &= 0xFFFFFFFF # a negative input becomes its 32-bit pattern
count = 0
while n:
n &= n - 1 # erase the lowest 1 bit
count += 1
return countfunction countOnes(n) {
n = n >>> 0; // view the value as unsigned 32-bit
let count = 0;
while (n !== 0) {
n = (n & (n - 1)) >>> 0; // erase the lowest 1 bit
count++;
}
return count;
}The JavaScript detail is worth saying aloud. Bitwise operators convert their operands to signed 32-bit integers, so the value 2^31 behaves like a negative number inside &. The >>> 0 turns the result back into an unsigned number so the loop condition and the count stay correct. Testing with the loop condition n > 0 instead of n !== 0 is a classic bug for the same reason.
Constant work with no loop
If the interviewer pushes for branch-free code, there is a well-known trick that counts in parallel: first add neighboring bits in pairs, then pairs of pairs, then bytes, and finally sum the four byte counts with one multiplication. It is hard to invent on the spot, so present it as something you have seen rather than something you derived.
def count_ones_parallel(n):
n &= 0xFFFFFFFF
n = n - ((n >> 1) & 0x55555555) # counts per 2-bit pair
n = (n & 0x33333333) + ((n >> 2) & 0x33333333) # counts per 4-bit group
n = (n + (n >> 4)) & 0x0F0F0F0F # counts per byte
return ((n * 0x01010101) & 0xFFFFFFFF) >> 24 # add the four bytesCost of each approach
| Approach | Time | Extra memory | Notes |
|---|---|---|---|
| Shift and test every bit | O(w), here 32 steps | O(1) | Simple and correct; does the same work for every input |
| Erase lowest 1 bit (n & (n - 1)) | O(k), at most 32 | O(1) | The expected answer; fast for sparse inputs |
| Byte lookup table | O(w / 8) table reads | 256 small entries | Good when called many times |
| Parallel counting with masks | Fixed number of operations | O(1) | Branch-free; hard to explain if you have not seen it |
Inputs to test
- Zero. The loop must not run at all.
- 2^31, a single 1 in the top position. Signed-integer bugs show up here.
- 2^32 - 1, all ones. The fast loop runs its maximum of 32 times.
- A negative value in a language with signed integers, if the interviewer allows it. In Python, -1 without masking would loop forever.
- Alternating patterns such as 0x55555555, which have exactly 16 ones.
Common slips
- Using an arithmetic right shift on a negative number in Java-like or C-like code, so the sign bit refills from the top and the loop never ends.
- Writing
n & 1 == 0in C, C++ or JavaScript, where==binds tighter than&, so the test meansn & (1 == 0). Bracket bit tests. - Converting to a binary string and counting characters without mentioning that it allocates a string; fine as a first idea, weak as a final one.
- Forgetting that a JavaScript number above 2^31 turns negative inside a bitwise expression.
- Explaining what the code does without explaining why n & (n - 1) removes exactly one bit.
How to explain it out loud
Fictional example
- Candidate
- The straightforward way is to look at the last bit, add it, shift, and do that 32 times. That works, but it ignores how many ones there actually are.
- Candidate
- There is a neat property: n minus one flips the lowest 1 to 0 and the zeros below it to ones. So n AND n minus one is n with its lowest 1 erased.
- Candidate
- I loop that until n is zero and count the rounds. That is one round per set bit, at most 32, and constant memory. In JavaScript I'll keep the value unsigned with a zero-fill shift so 2^31 does not turn negative.
Related problems
Counting Bits asks for this count for every number up to n and rewards reusing answers. Reverse Bits uses the same shift-and-mask moves to rebuild a number backwards. Missing Number shows another bit identity, x ^ x = 0, doing useful work. For the full interview loop around these warm-ups, see software engineer interview questions.
Practicing with Natively
Bit problems are easy to get almost right. In a practice session, Natively can read the problem from a screenshot on your Mac or Windows PC, suggest the n & (n - 1) idea or the masking step you forgot, and point at inputs such as 2^31 that tend to break a first draft. It also transcribes your mock interview, so afterwards you can check whether you explained why the trick works or only recited it.
Questions people ask
What is the fastest simple way to count 1 bits?
Repeat n = n & (n - 1) until n is zero and count the steps. Each step erases the lowest 1 bit, so the loop runs once per set bit, at most 32 times for a 32-bit value.
Why does n & (n - 1) remove the lowest set bit?
Subtracting 1 turns the lowest 1 bit into 0 and every 0 below it into 1. ANDing with the original clears that position and everything below it, while the higher bits stay the same.
How do you count bits of a negative number in Python?
Mask it first with n & 0xFFFFFFFF to get its 32-bit pattern. Python integers have no fixed width, so shifting a negative number right never reaches zero.
What is the time complexity of Number of 1 Bits?
O(1) for a fixed 32-bit width. More precisely, the shift loop always takes 32 steps and the n & (n - 1) loop takes one step per set bit.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
