Start learning free

LESSON 212 OF 285 · WHILE LOOPS - CHALLENGES

Number of Digits in JavaScript: 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

    JAVASCRIPT · WHILE LOOPS - CHALLENGES

    No Of Digits in JavaScript, explained

    Problem overview

    The method noOfDigits receives a non-negative integer n and returns how many digits it has. 542 has 3, and 100 has 3 too, because the zeros are digits. The number 0 is written with one digit, so noOfDigits(0) is 1.

    Approach: count how many times you can drop a digit

    Dividing a whole number by 10 and rounding down removes its last digit: 542 becomes 54, then 5, then 0. That took three divisions, and 542 has three digits. So the digit count equals the number of divisions needed to reach 0.

    The loop works while n is greater than 0, which makes 0 a special case. For 0, the loop would run zero times and count no digits, though the right answer is 1. The method handles that one input before the loop.

    Step by step

    1. Return 1 for zero. If n is 0, return 1 immediately. Without this, the loop would report 0 digits.
    2. Declare count with let, starting at 0. It counts the digits removed so far, and it changes inside the loop.
    3. Loop while n > 0. One pass per digit.
    4. Add 1 to count with ++.
    5. Drop the last digit. n / 10 in JavaScript keeps the fraction, so 542 / 10 is 54.2. Math.floor rounds it down to 54.
    6. Return count after the loop.

    The solution in JavaScript

    class Solution {
        noOfDigits(n) {
            if (n == 0) {
                return 1;
            }
            let count = 0;
            while (n > 0) {
                count++;
                n = Math.floor(n / 10);
            }
            return count;
        }
    }
    

    For noOfDigits(542), the values after each pass are:

    Passncount
    1541
    252
    303
    • == against ===. The lesson writes n == 0. For two numbers, == and === give the same answer. Loose equality converts types first, so "0" == 0 is true, while "0" === 0 is false. Most JavaScript style guides prefer ===, and it would work here too.
    • The early return ends the method. The lines after the if run only when n isn't 0, so no else is needed.

    How many passes

    Time: O(d), where d is the number of digits, which grows like log10(n). The loop never runs more than 10 times for inputs up to 10^9. Space: O(1).

    Why Math.floor matters

    In JavaScript, / is real division. Starting from 542 and writing n = n / 10, the values are 54.2, 5.42, 0.542, 0.054200000000000005 and so on. The number keeps shrinking but never reaches exactly 0 in a useful number of passes, so the loop would count far more than 3. Rounding down after each division keeps n a whole number: 542, 54, 5, 0.

    What the special case prevents

    Take the first if away and call the method with 0. The loop condition 0 > 0 is false at once, no pass runs, and the method returns 0. The correct answer is 1, because the number 0 is written with a single digit. That is the only input where the loop's count and the true count disagree, so one early return fixes it.

    The trailing zeros case

    For n = 100 the passes leave n at 10, then 1, then 0, with count at 1, 2 and 3. Zeros at the end are removed like any other digit, which is why the answer is 3 and not 1.

    Another way to count, and why the loop still matters

    JavaScript can also answer this question without arithmetic: String(n).length converts the number to text and counts the characters. It needs no special case, because String(0) is "0", a text of length 1. For 542 it gives 3, and for 1000000000 it gives 10.

    The string route has limits. It counts every character, so a negative number such as -45 gives 3, because the minus sign is counted as well. The loop version is the one to learn here, because the same pattern of testing the last digit and dropping it turns up in many digit problems: summing digits, reversing a number, checking for palindromes. Writing it by hand also shows how decimal notation works.

    The special case for 0 shows up in many loops of this kind. A loop that runs "while there is something left" runs zero times when nothing is left at the start, even when the correct answer for that input is not zero. Checking the smallest input by hand, before trusting the loop, is a good habit.

    Edge cases and common mistakes

    • Zero. noOfDigits(0) returns 1. It is the one input where counting divisions fails.
    • Trailing zeros. noOfDigits(100) returns 3: 100 becomes 10, then 1, then 0, which is three divisions.
    • The largest input. noOfDigits(1000000000) returns 10.
    • Forgetting Math.floor. 542 / 10 is 54.2, and the fractions keep n above 0 for many more passes, so the count comes out too high.
    • Counting before the loop. Starting count at 1 would make every non-zero input too large by one and still need the special case for 0. Starting at 0 and counting inside the loop is correct.

    Testing

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