L1 · FoundationsNumbers & loops~3 min · 5 tests

Sum of the Digits of a Number

Add up the digits of an integer with % 10 and // 10 instead of string conversion. Handle negatives and zero, and learn why it is O(number of digits).

The problem

Return the sum of the digits of the integer n. Treat negative numbers by their absolute value. Use arithmetic (% and //), not str().

Examples

  1. Example 1

    Input

    digit_sum(1234)

    Expected output

    10
  2. Example 2

    Input

    digit_sum(9)

    Expected output

    9

+ 3 hidden tests on Submit.

Edge cases to ask about

  • Zero
  • Negative numbers

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · digit_sum
    ⌘/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
    str(n) and sum the charactersO(d)O(d)Readable, but builds a string.
    best% 10 and // 10O(d)O(1)d = number of digits = O(log n).
    Walkthrough of the optimal approach (try it yourself first)

    n % 10 gives the last digit; n // 10 removes it. Repeat until n is 0. The loop runs once per digit — about log₁₀(n) times — which is why digit problems are O(log n).

    Complexity: O(log n) time, O(1) space. Each loop removes one digit, and a number n has about log₁₀(n) digits.

    Reveal the reference solution
    def digit_sum(n):
        n = abs(n)
        total = 0
        while n:
            total += n % 10
            n //= 10
        return total

    Follow-ups interviewers ask

    • Keep summing until one digit remains (digital root) — in O(1).

    Frequently asked interview questions

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

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

    The optimal solution runs in O(log n) time and O(1) auxiliary space. Each loop removes one digit, and a number n has about log₁₀(n) digits.

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

    str(n) and sum the characters: O(d) time, O(d) space. Readable, but builds a string. % 10 and // 10: O(d) time, O(1) space. d = number of digits = O(log n).

    What follow-up questions do interviewers ask about Sum of the Digits of a Number?

    Keep summing until one digit remains (digital root) — in O(1).