ProgrammingVery hardAmazon OA · Goldman Sachs OA

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 n = 360
while (n > 0)
    Print n & (-n)
    n = n - (n & (-n))
end while
  1. A. 256 64 32 8
  2. B. 8 16 32 64
  3. C. 8 32 64 256
  4. D. 2 4 8 16

Correct answer: C. 8 32 64 256

In two's complement, n & (−n) keeps only the lowest set bit. 360 = 256 + 64 + 32 + 8, and the loop peels these off from the lowest: 8 32 64 256.

More Pseudocode and Code Tracing questions

Exams that ask this topic