ProgrammingVery hardTCS NQT · Accenture

The procedure below counts the numbers i from 1 to 100 whose binary form has exactly three 1 bits (bits are counted by repeatedly taking n mod 2 and dividing n by 2). What is printed?

The procedure below counts the numbers i from 1 to 100 whose binary form has exactly three 1 bits (bits are counted by repeatedly taking n mod 2 and dividing n by 2). What is printed?
count = 0
for i = 1 to 100
    bits = number of 1 bits of i
    if bits == 3 then count = count + 1
end for
Print count
  1. A. 21
  2. B. 26
  3. C. 33
  4. D. 4

Correct answer: C. 33

Exactly 33 of the numbers 1 to 100 have three 1 bits. Counting those with two 1 bits gives 21, counting those with four 1 bits gives 26, and counting the bit lengths instead of the 1 bits gives 4 numbers with bit length 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic