ProgrammingHardTCS NQT · Accenture pattern

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

What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, ^ is bitwise XOR, << and >> are left and right shifts.)
Integer a = 29, b = 0
while (a > 0)
    b = (b << 1) | (a & 1)
    a = a >> 1
end while
Print b
  1. A. 23
  2. B. 15
  3. C. 27
  4. D. 29

Correct answer: A. 23

Each pass moves the lowest bit of a onto the end of b, so b gets a's bits in reverse. 29 = 11101 reversed is 10111 = 16 + 4 + 2 + 1 = 23.

More Pseudocode and Code Tracing questions

Exams that ask this topic