ProgrammingHard

Which loop computes the number of trailing zeros of n in O(number of zeros) time for an unsigned n greater than zero?

  1. A. for (c = 0; n; c++) n = n / 10;
  2. B. while ((n & 1) == 0) { n >>= 1; c++; }
  3. C. for (c = 0; c < 32; c++) n = n + n;
  4. D. while (n) n = n & (n - 1);

Correct answer: B. while ((n & 1) == 0) { n >>= 1; c++; }

The loop stops at the first set bit, so its cost is the number of trailing zeros. The other loops count digits, shift for a fixed count, or count set bits.

More C Programming questions

Exams that ask this topic