Beginner Β· while + division
Count the Digits
Read an integer and print how many digits it has. This is the loop that teaches % 10 and / 10 β the two operations behind every digit-manipulation problem.
Problem
Input: one integer n (β10βΉ β€ n β€ 10βΉ).
Output: the number of digits in n (the minus sign doesn't count).
Sample:
| Input | Output |
|---|---|
7 | 1 |
2048 | 4 |
0 | 1 |
Your solution
Custom input for "Run my input"
Judging runs entirely in your browser. Hidden tests include n = 0 and negative n.
Stuck? Hints
Hint 1 β the two operations
n % 10 is the last digit; n / 10 is the number with the last digit removed (integer division!). 2048 β 204 β 20 β 2 β 0 β count the steps until zero.
Hint 2 β the two traps
Trap 1: while (n > 0) never runs for n = 0 β you'd print 0 digits, but 0 has one digit. Trap 2: negative input loops forever with n > 0β¦ take Math.Abs(n) first.
Solution (try first!)
int n = Math.Abs(int.Parse(Console.ReadLine()));
int digits = 0;
do
{
digits++;
n = n / 10;
} while (n > 0);
Console.WriteLine(digits);
// the shortcut: ToString() and let Length count
int n = int.Parse(Console.ReadLine());
Console.WriteLine(Math.Abs(n).ToString().Length);
The do-while handles n = 0 for free β the body runs once before the condition is checked. You've finished the problem set: revisit the list or read why integer division makes the peel loop work.