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

Bit-by-bit counting with shift and mask
def count_bits(n):
    count = 0
    while n > 0:
        count += n & 1
        n >>= 1
    return count

Common follow-up questions