Count all Digits of a Number

Pattern: Maths basics

easy

Count how many digits a whole number has, by peeling digits off the right end.

The problem

You are given a whole number n that is zero or more and fits in a 32-bit integer. Return how many digits it has when written in everyday decimal form. For example, 12345 has 5 digits, and 0 has 1 digit.

On the original site the problem is written a little differently, so use the link above for its exact wording. The function in this guide is called countDigits.

Think first

Take 12345 and answer these on paper before you read on.

  • What single step turns 12345 into 1234? And 1234 into 123?
  • If you repeat that step, how will you know when to stop?
  • What should happen for 0?

Hints

    Brute force, and why it fails

    The most direct idea is to write the number as text and measure the text. In most languages that is one line, and it is a perfectly good answer for a quick script. Another idea is the formula floor(log10(n)) + 1, which works on paper but can be off by one for numbers like 1000 because decimals are stored approximately.

    Neither idea is too slow, since a number has at most 10 digits. The reason to do it with arithmetic instead is the next section: the move you are about to learn, peeling digits with % 10 and / 10, is the engine behind reversing a number, checking palindromes, summing digits and many more problems in this pattern. Text conversion hides that move.

    The key insight

    Dividing by 10 removes the last digit, so the number of digits is the number of times you can divide by 10 before reaching 0. The loop count is the answer.

    Dry run

    10 
    21 
    32 
    43 
    54 
    n12345
    count0

    Start with n = 12345 and a count of 0. The array shows the digits of n, left to right.

    Step 1 of 6

    The plan

    if n == 0:
        return 1            # 0 is written with one digit
    
    count = 0
    while n > 0:
        count = count + 1   # one more digit found
        n = n div 10        # drop the last digit
    return count
    

    Complexity

    Time
    O(d)
    Space
    O(1)

    d is the number of digits, and each round does a constant amount of work. Since a 32-bit number has at most 10 digits, this is effectively instant. Only a few variables are used, so the extra space is constant.

    Edge cases

    • n = 0 must return 1. The while loop would not run at all, so it needs its own check.
    • A single digit such as 7 runs the loop once.
    • Numbers ending in zeros such as 100 still count every digit, so the answer is 3.
    • The largest 32-bit number, 2147483647, has 10 digits and fits easily.
    I've built my logic, show the code

    Java

    class Solution {
        public int countDigits(int n) {
            if (n == 0) {
                return 1;
            }
            int count = 0;
            while (n > 0) {
                count++;
                n = n / 10;
            }
            return count;
        }
    }

    C++

    class Solution {
    public:
        int countDigits(int n) {
            if (n == 0) {
                return 1;
            }
            int count = 0;
            while (n > 0) {
                count++;
                n = n / 10;
            }
            return count;
        }
    };

    Python

    class Solution:
        def countDigits(self, n):
            if n == 0:
                return 1
            count = 0
            while n > 0:
                count += 1
                n = n // 10
            return count

    Common mistakes

    • Forgetting the n == 0 case and returning 0.
    • Using floating-point log10 and getting 3 digits for 1000 on some machines.
    • Starting the count at 1 and also counting inside the loop, which gives one too many.
    • Dividing with / in Python 3, which gives a decimal; use // for whole-number division.

    Similar problems