Find the number of digits of a given number

For any given number greater than 9, we would need to find the number of digits present in the number by pure logic. For this, we would use the standard divisibility rule of 10 in which when a number is divided by 10 the last digit of the number is returned as the remainder and the remaining digits are returned as the quotient.

For example : 6234 divided by 10 leaves 4 as remainder since 10 divides 6234 by 623 times.

We use this rule to strip the numbers and count them.


        public static int NumberOfDigits(int n)
        {
            int counter = 0;
            while (n > 0)
            {
                n = n / 10;
                counter++;
            }
            return counter;
        }
        

How it works:

For any given number, say 6234 the loop runs till the number is a 0.

We iteratively divide the number by 10 and assign the quotient to itself. So

n = 6234 / 10 = 623
n = 623 / 10 = 62
n = 62 / 10 = 6
n = 6 / 10 = 0

We get the counter which will be set to 4 at the end of loop.


Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *