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.

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.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.