What does the following Python function compute for a positive integer n?

def mystery(n):
count = 0
while n > 0:
count += n & 1
n >>= 1
return count

Answer and explanation

Correct answer: C. The number of set bits (1s) in the binary representation of n

  1. Step 1: Examine bitwise operations: `n & 1` checks the least significant bit (1 if odd, 0 if even).
  2. Step 2: `n >>= 1` shifts the bits right by one position on each iteration. Summing `n & 1` counts all 1s (set bits/Hamming weight) in the binary representation of .
Answer
The number of set bits (1s) in the binary representation of n.
Why not the others: Decimal digit sums require `% 10` and `// 10`; prime factors and square roots require arithmetic factoring routines.

Practise more Algorithms and Python Programming.

Free questions with an explanation for every one, and full timed EmSAT Achieve (UAE) mock tests.