ProgrammingHardGoldman Sachs OA · Infosys SP

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

What will be the output of the following pseudocode? (| is OR, & is AND, << and >> are shifts)
Integer c = 0, r, x
for (each n from 1 to 100)
    r = 0
    x = n
    while (x > 0)
        r = (r << 1) | (x & 1)
        x = x >> 1
    end while
    if (r == n)
        c = c + 1
    end if
end for
Print c
  1. A. 16
  2. B. 10
  3. C. 20
  4. D. 19

Correct answer: D. 19

r is n with its binary digits reversed, so c counts binary palindromes up to 100. By length: 1 (1), 1 (11), 2 (101, 111), 2, 4, 4, and with 7 bits only those ≤ 100 (= 1100100): 1000001, 1001001, 1010101, 1011101, 1100011 (99) → 5. Total 1 + 1 + 2 + 2 + 4 + 4 + 5 = 19.

More Pseudocode and Code Tracing questions

Exams that ask this topic