The Bit Counter
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- Egen
Problem
Given a non-negative integer n, return the number of 1-bits in its binary representation. Do not convert to a binary string; use bitwise operations.
How many lights are on in the binary representation?
Example 1
Input:
n = 11
Output:
3
Example 2
Input:
n = 128
Output:
1
Worked solution and explanation
Why this problem exists in real interviews
Counting set bits without string conversion tests bitwise operations: right-shift and AND masking. It is a fundamental low-level operation that reveals whether you understand binary representation.
Break down the requirements
Step 1: Check the lowest bit
n & 1 is 1 if the lowest bit is set, 0 otherwise.
Step 2: Right-shift to expose the next bit
n >>= 1 moves all bits one position to the right, discarding the lowest.
Step 3: Repeat until n is 0
When all bits have been shifted out, the count is complete.
The solution
def count_bits(n):
count = 0
while n > 0:
count += n & 1
n >>= 1
return countCommon follow-up questions
- Can you count bits in O(number of set bits) time? (Tests Brian Kernighan's algorithm: `n &= (n - 1)` clears the lowest set bit each iteration.)
- How would you handle negative numbers? (Tests understanding of two's complement. In Python, negative integers have infinite precision, so you would need to mask to a fixed width.)
- How would you count bits for all numbers from 0 to n? (Tests the DP approach: `bits[i] = bits[i >> 1] + (i & 1)` for building a lookup table.)