Beginner · loops + integer math
Count the Digits
Read a positive integer and print how many digits it has. Introduces the most useful number trick in beginner problems: chopping digits off with / 10 and % 10.
At a glanceCount the digits of N by dividing by 10 in a while-loop until N reaches 0 — the loop shape every later digit problem reuses.
Problem
Input: one positive integer N (1 ≤ N ≤ 10⁹).
Output: the number of digits in N.
Samples:
| Input | Output |
|---|---|
12345 | 5 |
7 | 1 |
Your solution
Custom input for "Run my input"
Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.
Stuck? Hints
Hint 1 — the chopping pattern
n % 10 gives the last digit; n / 10 removes it (integer division! see why 7/2 = 3). So 12345 becomes 1234 becomes 123… until it hits 0. Count how many chops that took.
Hint 2 — choosing the loop
You don't know in advance how many iterations you need — that's a while job: while (n > 0) { count++; n /= 10; }. Compare with the for vs while guide: unknown iteration count → while.
Solution (try it first!)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int count = 0;
while (n > 0) {
count++;
n /= 10;
}
cout << count << endl;
return 0;
}
This chopping pattern is half of the next problem too — Reverse a Number uses the same two moves in a different order. That's how algorithmic thinking works: patterns recombine.
Deep dive
Why this works
Integer division by 10 peels off the last digit; that pair / 10 and % 10 is the entire basis of digit manipulation, and it shows up in half the problems on this site.
The cost
O(d) where d is the digit count — at most 10 for an int, so effectively constant.
Where it goes wrong
while (n > 0)returns 0 digits for n = 0. Zero needs its own answer.log10(n) + 1looks clever and breaks on 0 and on floating-point rounding at exact powers of ten.
Next step
Add the digits you are peeling: Sum of Digits.
Two things to remember
- / 10 removes the last digit; % 10 reads it.
- Zero is the input that breaks every digit loop.
🐞 This version fails — open it and try
while (n >= 10) stops one digit early
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int count = 0;
while (n >= 10) {
n /= 10;
count++;
}
cout << count << endl;
return 0;
}