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:

InputOutput
71
20484
01

Your solution

Program.cs β€” 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.