ProgrammingHard

Which C code correctly counts the digits of n = 10^9 in a fast enough way for many queries?

  1. A. for (int i = 0; i < n; i++) if (n == i * 10) d++;
  2. B. int d = (int)log10(n);, with the value not used
  3. C. int d = n; for (int i = 0; i < d; i++) d /= 10;
  4. D. unsigned long long m = n; int d = 0; do { d++; m /= 10; } while (m);

Correct answer: D. unsigned long long m = n; int d = 0; do { d++; m /= 10; } while (m);

The do-while divides by 10 once per digit, so it takes about 10 steps for 10^9. The other versions loop over n itself or produce the wrong count.

More C Programming questions

Exams that ask this topic