#258

Add Digits

Easy Digital root

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Keep replacing a number with the sum of its digits until only one digit is left, and return that digit.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: keep summing digits until one digit is left (the "digital root").

Why this works: a number and its digit sum have the same remainder mod 9, so the final digit is fixed by num mod 9, with multiples of 9 giving 9.

Example: num = 38

3 + 8 = 11 → 1 + 1 = 2formula: 1 + (38 - 1) % 9 = 1 + 1 = 2 ✓

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using num % 9 directly, which gives 0 for 9, 18, 27… instead of 9.