ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (Integers are in two's complement, so −i flips the bits of i and adds 1; & is bitwise AND.)

What will be the output of the following pseudocode? (Integers are in two's complement, so −i flips the bits of i and adds 1; & is bitwise AND.)
Integer s = 0
for (each i from 1 to 32)
    s = s + (i & (-i))
end for
Print s
  1. A. 96
  2. B. 528
  3. C. 80
  4. D. 112

Correct answer: D. 112

i & (−i) keeps only the lowest set bit of i. Among 1…32, 16 numbers have lowest bit 1, 8 have 2, 4 have 4, 2 have 8, 1 has 16 (namely 16) and 1 has 32. Each group from 1 to 16 contributes 16, so the sum is 5 × 16 + 32 = 112. 528 = 1 + … + 32 treats i & (−i) as i; 96 forgets the 32.

More Pseudocode and Code Tracing questions

Exams that ask this topic