ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, << and >> are shifts.)

What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, << and >> are shifts.)
Integer x = 22, r = 0
for (each i from 1 to 8)
    r = (r << 1) | (x & 1)
    x = x >> 1
end for
Print r
  1. A. 13
  2. B. 26
  3. C. 208
  4. D. 104

Correct answer: D. 104

The loop takes bits of x from the right and pushes them into r from the right, so r ends up as x's 8 bits in reverse order. 22 = 00010110, reversed 01101000 = 64 + 32 + 8 = 104. 13 = 1101 reverses only the significant bits 10110 → 01101, forgetting that the loop runs 8 times and the leading zeros become trailing zeros.

More Pseudocode and Code Tracing questions

Exams that ask this topic