Skip to content
Problem 258 · LeetCode 258(opens in a new tab)

Add Digits

EasyMath

You are given a non-negative integer num. Add up its digits to get a new number. If that number has more than one digit, add up its digits too, and keep going.

Return the single digit you end up with. Can you do it in O(1) time, with no loop or recursion?

Example 1

Input:  num = 57
Output: 3
Why:    5 + 7 = 12, then 1 + 2 = 3
2 more examples and the constraints

Example 2

Input:  num = 0
Output: 0
Why:    zero is already one digit

Example 3

Input:  num = 6
Output: 6
Why:    a single digit is returned as it is

Constraints

  • 0 ≤ num ≤ 2³¹ − 1

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Add the digits until one is leftO(log n)
  2. Digital root formulaO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeOperations for num = 2,147,483,647Verdict
Add the digitsO(log n)
Fine, but uses loops
Digital root formulaO(1)
Best; meets the follow-up

n = num; it has about log₁₀ n digits.

Edge cases to test

  • Zero. The only input whose answer is 0. The formula needs its own check for it.
  • Already one digit. 6 returns 6; the simulation loop never runs.
  • Multiples of 9. 18 and 999,999,999 both return 9, not 0.
  • The largest input. 2,147,483,647 has digit sum 46, then 10, then 1.

Common mistakes

  • Returning num % 9, which gives 0 for 9, 18 and every other multiple of 9.
  • Forgetting that num = 0 must return 0, not 9 or 1.
  • Stopping after one round of adding, which can still leave two digits (199 gives 19 first).

How to talk through it

  1. 1Clarify. Is num ever negative? What should 0 return?
  2. 2Simulate first. Peel off digits and add until one digit is left; it is already fast.
  3. 3Look for a pattern. List the answers for 1, 2, 3 and so on: they cycle 1 to 9.
  4. 4Explain the math. 10 is 1 more than 9, so a number and its digit sum agree mod 9. Shift by one so multiples of 9 give 9.
  5. 5Test out loud. Try 0, 9, 18 and 57.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?