ProgrammingVery hardGoldman Sachs OA · Infosys SP

What will be the output of the following pseudocode? (& is bitwise AND on two's-complement integers)

What will be the output of the following pseudocode? (& is bitwise AND on two's-complement integers)
Integer c = 0
for (each i from 0 to 20)
    if ((i & (i - 1)) == 0)
        c = c + 1
    end if
end for
Print c
  1. A. 5
  2. B. 6
  3. C. 4
  4. D. 21

Correct answer: B. 6

i & (i − 1) clears the lowest 1-bit, so it is 0 for powers of two: 1, 2, 4, 8, 16. But it is also 0 for i = 0 (0 & −1 = 0), so the 'power of two' test wrongly accepts 0: c = 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic