Data Structures & AlgorithmsModerateTCS NQT · Accenture

Problem: In a bit-trick loop, n = 0b101101 is processed by repeatedly computing n &= n − 1 until n becomes 0. How many iterations are performed?

  1. A. 5
  2. B. 3
  3. C. 4
  4. D. 6

Correct answer: C. 4

n &= n − 1 clears the lowest set bit each time, so the loop runs once per set bit. Dividing by 2 instead counts the bit length, which is a different number.

More Coding Interview Problems questions

Exams that ask this topic