Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count the total number of 1 bits in all integers from 0 to n without iterating over them: bit b repeats a pattern of 2^b zeros then 2^b ones.

Problem: Count the total number of 1 bits in all integers from 0 to n without iterating over them: bit b repeats a pattern of 2^b zeros then 2^b ones.
def total_bits(n):
    total, b = 0, 0
    while (1 << b) <= n:
        cycle = 1 << (b + 1)
        total += (n + 1) // cycle * (1 << b) + max(0, (n + 1) % cycle - (1 << b))
        b += 1
    return total
print(total_bits(5), total_bits(16), total_bits(1000))
What is printed?
  1. A. 7 32 4938
  2. B. 7 33 4938
  3. C. 7 33 5000
  4. D. 8 33 4938

Correct answer: B. 7 33 4938

For bit b, the numbers 0..n contain (n + 1) // 2^(b+1) full cycles, each with 2^b ones, plus a partial cycle that contributes max(0, remainder − 2^b). 0..5: 0, 1, 1, 2, 1, 2 → 7. 0..16: 32 ones in 0..15 plus 1 for 16 → 33. 0..1000 → 4938 (a brute-force popcount sum agrees). O(log n).

More Coding Interview Problems questions

Exams that ask this topic