L1 · FoundationsNumbers & loops~3 min · 5 tests

Count the Digits in a Number

Count how many digits an integer has using a loop with // 10, then see the O(1) logarithm shortcut and why it can be wrong. Live Python tests.

The problem

Return how many digits the integer n has. 0 has one digit; ignore the sign.

Examples

  1. Example 1

    Input

    count_digits(12345)

    Expected output

    5
  2. Example 2

    Input

    count_digits(0)

    Expected output

    1

+ 3 hidden tests on Submit — 20 nines.

Edge cases to ask about

  • Zero
  • Negative numbers
  • Very large numbers

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · count_digits
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Divide by 10 until zeroO(log n)O(1)
    len(str(abs(n)))O(log n)O(log n)Simple and exact.
    bestfloor(log10(n)) + 1O(1)O(1)Floating-point error makes it wrong for very large n.
    Walkthrough of the optimal approach (try it yourself first)

    Divide by 10 until the number is 0, counting the steps — one per digit. Zero needs a special case because the loop would not run at all.

    math.log10 looks O(1), but floating-point rounding makes it give wrong answers for numbers like 10**15 - 1. The hidden test checks a 20-digit number.

    Complexity: O(log n) time, O(1) space. Each division removes one digit.

    Reveal the reference solution
    def count_digits(n):
        n = abs(n)
        if n == 0:
            return 1
        count = 0
        while n:
            n //= 10
            count += 1
        return count

    Follow-ups interviewers ask

    • Why can the log10 version be wrong?

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Count the Digits in a Number in Python?

    The optimal solution runs in O(log n) time and O(1) auxiliary space. Each division removes one digit.

    What is the brute-force approach, and how do you optimise it?

    Divide by 10 until zero: O(log n) time, O(1) space. len(str(abs(n))): O(log n) time, O(log n) space. Simple and exact. floor(log10(n)) + 1: O(1) time, O(1) space. Floating-point error makes it wrong for very large n.

    What follow-up questions do interviewers ask about Count the Digits in a Number?

    Why can the log10 version be wrong?