2026-09-12
count_digits.cpp
int count_digits(int n) {
// write this: return the number of decimal digits in n
// (n is guaranteed to be positive)
}
正の整数nが十進で何桁かを返すcount_digitsを実装してください。forではなくwhileを使うとしたら、それはなぜでしょうか——考えながら書いてみてください。
Reference
int count_digits(int n) {
int count = 0;
while (n > 0) {
n /= 10;
++count;
}
return count;
}
forは「繰り返す回数(や範囲)が先に分かっている」ときに向いていますが、桁数はまさに今数えている最中の値であり、始める前には分かりません。「nが0になるまで」という終了条件だけがあらかじめ分かっている状況はwhileの得意分野です。これは参考実装であり、唯一の正解ではありません。