ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (& is bitwise AND.)

What will be the output of the following pseudocode? (& is bitwise AND.)
Integer c = 0, x
for (each i from 0 to 63)
    x = i
    while (x > 0)
        x = x & (x - 1)
        c = c + 1
    end while
end for
Print c
  1. A. 192
  2. B. 384
  3. C. 64
  4. D. 160

Correct answer: A. 192

x & (x − 1) clears the lowest set bit, so the inner loop runs once per 1-bit of i. Over 0…63 every one of the 6 bit positions is set in exactly half the numbers, 32, so the total is 6 × 32 = 192. 384 assumes the inner loop runs 6 times per number; 64 counts the outer iterations only.

More Pseudocode and Code Tracing questions

Exams that ask this topic