ProgrammingHardTCS NQT · Infosys · Cognizant GenC

Consider the pseudocode. sum = 0 for i = 1 to 15: n = i while n != 0: n = n AND (n - 1) sum = sum + 1 print sum What is printed?

  1. A. 32
  2. B. 30
  3. C. 34
  4. D. 36

Correct answer: A. 32

n AND (n-1) clears the lowest set bit, so the inner loop runs once per 1-bit of i. The total number of 1-bits in 1..15 is 4*8 = 32 (each of the 4 bit positions is set in 8 numbers).

More Pseudocode and Code Tracing questions

Exams that ask this topic