ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (>> is right shift, & is bitwise AND)

What will be the output of the following pseudocode? (>> is right shift, & is bitwise AND)
Integer bits[0..15], total = 0
bits[0] = 0
for (each i from 1 to 15)
    bits[i] = bits[i >> 1] + (i & 1)
end for
for (each i from 0 to 15)
    total = total + bits[i]
end for
Print bits[13], total
  1. A. 3 32
  2. B. 3 30
  3. C. 2 32
  4. D. 4 32

Correct answer: A. 3 32

bits[i] reuses the count for i with its last bit removed, so bits[i] is the number of 1's in i: bits[13] = bits[1101₂] = 3. Over 0 to 15, each of the 4 bit positions is 1 in exactly 8 numbers: total 32.

More Pseudocode and Code Tracing questions

Exams that ask this topic