Start learning free

LESSON 211 OF 281 · WHILE LOOPS - CHALLENGES

Number of Digits in C++: Counting With a while Loop

Practice Read the full explanation

Given a non-negative integer n, return how many digits it has.

The digits are the figures from 0 to 9 that n is written with. Dividing a number by 10 without the remainder removes its last digit (542 becomes 54), so you can count how many times that happens until the number is 0. The number 0 itself has one digit.

 

Example 1:

Input: n = 542
Output: 3
Explanation: 542 is written with three digits: 5, 4 and 2.

Example 2:

Input: n = 100
Output: 3
Explanation: The zeros are digits too: 1, 0 and 0.

Example 3:

Input: n = 0
Output: 1
Explanation: 0 is written with one digit.

 

Constraints:

  • 0 <= n <= 109
STEP 1 OF 6
    Ctrl + Enter to check

    C++ · WHILE LOOPS - CHALLENGES

    No Of Digits in C++, explained

    Problem overview

    The function noOfDigits receives a non-negative integer n, up to 1,000,000,000, and returns how many digits it is written with. The number 542 has three digits, 100 has three (the zeros count), and 0 has one.

    Approach

    In an int, dividing by 10 drops the last digit: 542 / 10 is 54. So the number of digits is the number of times you can divide by 10 before reaching 0. A loop that divides by 10 and adds 1 to a counter on each pass does exactly that.

    There is one number this loop can't handle. For 0, the condition n > 0 is false from the start, so the loop would count no digits, but 0 is written with one. The function therefore deals with 0 first, before the loop.

    The loop on n = 542 looks like this, with the count after each pass:

    n=54 count=1
    n=5 count=2
    n=0 count=3
    

    This kind of loop, where the number of passes depends on the size of the value, is common. A value below 1,000,000,000 has at most nine digits, so the loop never runs more than ten times, whatever the input. The cost grows with the number of digits, not with the value itself.

    Step by step

    1. Handle zero first. If n == 0, return 1.
    2. Create count as an int starting at 0. No digit has been removed yet.
    3. Start a while loop that runs while n > 0. It will run once for every digit.
    4. Add 1 to count with ++. One pass is one digit.
    5. Replace n with n / 10. When the last digit is gone, n is 0 and the loop stops.
    6. Return count.

    The solution in C++

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

    A few details:

    • Integer division. Both n and 10 are int, so / discards the remainder: 542 becomes 54, then 5, then 0. That is three passes.
    • count++. The increment operator adds 1 to the variable. Here it is used as a statement on its own, so count++ and ++count do the same thing.
    • n is a copy. The function receives its argument by value, so changing n inside doesn't change the caller's variable.

    Other ways to count digits

    Two other ideas come up often, and it helps to know why the lesson doesn't use them.

    • Converting to text. to_string(n).size() builds a string of the number's digits and returns its length. It gives 3 for 542, 3 for 100, 1 for 0 and 10 for 1000000000, so it handles zero without a special case. It allocates a string, though, and the lesson is about practising the loop.
    • Logarithms. floor(log10(n)) + 1 also gives the right count for positive numbers, but log10(0) is minus infinity, so zero needs its own check again. It also moves the work into floating-point arithmetic, which is something to avoid when exact integer counts are needed.

    The division loop uses only integers and shows directly what "a digit" means for a number stored as a value: something you can remove with / 10.

    A loop that runs at least once

    The special case for 0 can also be avoided with a do ... while loop, which checks its condition after the body, so the body always runs once:

    int count = 0;
    do {
        count++;
        n = n / 10;
    } while (n > 0);
    

    With this loop, 0 counts one digit, then becomes 0 again and stops. It returns 3, 3, 1, 1 and 10 for 542, 100, 0, 7 and 1000000000. The lesson's version keeps the zero check separate, which makes the reason for it visible.

    Complexity

    Time: O(d), where d is the number of digits of n. Each pass removes one digit and does a constant amount of work. In other words the time is proportional to the logarithm of n, not to n.

    Space: O(1). The function uses one counter and its own copy of n.

    Edge cases and common mistakes

    • Zero. Without the first if, noOfDigits(0) would return 0. With it, the answer is 1.
    • Numbers with zeros. For 100 the loop passes three times: 100 becomes 10, then 1, then 0. The result is 3.
    • The largest input. 1000000000 has ten digits, and 999999999, just below it, has nine. Both fit in an int.
    • Single digits. 7 becomes 0 after one division, so the answer is 1.
    • Dividing the wrong way. If the loop forgets n = n / 10, n never reaches 0 and the loop doesn't end.

    Testing

    • n = 542 gives 3.
    • n = 100 gives 3.
    • n = 0 gives 1.
    • n = 7 gives 1.
    • n = 999999999 gives 9.
    • n = 1000000000 gives 10.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free