Digits in a number
Last updated:
8/22/2020
⁃
Difficulty:
Easy
Create a program in C# to calculate how many digits has a positive integer.
If the user enters a negative integer, the program must show a warning message, and proceed with the equivalent positive number.
Input
112
-5345
Output
2 digits
(Warning: it is a negative number)
4 digits
Solution
using System;
public class DigitsNumber
{
public static void Main(string[] args)
{
int x = Convert.ToInt32(Console.ReadLine());
int digits = 0;
if (x < 0)
{
Console.WriteLine("(Warning: it is a negative number)");
x = -x;
}
while (x > 0)
{
x /= 10;
digits++;
}
if (digits == 0)
{
digits = 1;
}
Console.WriteLine("{0} digits", digits);
}
}