Start learning free

LESSON 217 OF 292 · WHILE LOOPS - CHALLENGES

Number of Digits in Swift: 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 7
    Ctrl + Enter to check

    SWIFT · WHILE LOOPS - CHALLENGES

    No Of Digits in Swift, explained

    Problem overview

    The function noOfDigits receives a non-negative integer n and returns how many digits it has. The number 542 has 3 digits and 100 has 3 too, since zeros count. The number 0 is written with one digit, so the answer for 0 is 1.

    Approach

    Dividing an Int by 10 with / drops the remainder and removes the last digit: 542 becomes 54, then 5, then 0. That takes three divisions, one per digit. So the plan is to count how many divisions it takes to reach 0.

    The loop has one blind spot. It runs while the number is greater than 0, and 0 is not greater than 0, so for n = 0 it would count nothing and return 0. The right answer is 1, so that case is handled first, before the loop.

    You could also convert the number to a String and take its count, which counts characters. The loop in this lesson stays with arithmetic, which is the skill the exercise practises. Both give the same answer for non-negative numbers.

    Here is the count for 542, one division at a time: 542 becomes 54 (count 1), 54 becomes 5 (count 2), and 5 becomes 0 (count 3). Then num is 0 and the loop stops, with count holding 3. Seeing the count rise once per division makes it clear why the loop condition decides everything: it must stay true exactly as long as at least one digit remains.

    Step by step

    1. Handle zero. If n == 0, return 1 right away.
    2. Copy n into var num. Parameters are constants in Swift, so the loop needs its own variable to change.
    3. Create var count = 0 for the digits removed so far.
    4. Loop while num > 0. Each turn removes one digit.
    5. Add 1 to count with += 1. Swift has no ++ operator.
    6. Replace num with num / 10.
    7. Return count after the loop.

    The solution in Swift

    class Solution {
        func noOfDigits(_ n: Int) -> Int {
            if n == 0 {
                return 1
            }
            var num = n
            var count = 0
            while num > 0 {
                count += 1
                num = num / 10
            }
            return count
        }
    }
    

    Swift details worth knowing:

    • No ++. Swift removed the increment operator. Writing count++ fails with cannot find operator '++' in scope; did you mean '+= 1'?.
    • var and let. num and count change, so they are var. Assigning to the parameter n would fail with cannot assign to value: 'n' is a 'let' constant.
    • Integer division truncates. Int / Int never gives a fraction, so each division cleanly drops the last digit.
    • The early return. A return inside an if ends the function immediately, so the code after it only runs for numbers other than 0.

    Edge cases and common mistakes

    • Zero. Without the first if, noOfDigits(0) would return 0.
    • Numbers ending in zeros. 100 goes 100, 10, 1, 0, which is three divisions, so the answer is 3.
    • The largest input. 1000000000 has 10 digits, and the loop runs 10 times.
    • Forgetting to shrink num. If the loop never divides, it never ends.
    • Counting after the loop with a wrong starting value. Starting count at 1 would be off by one for every number except 0, which is handled separately.

    Testing

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