231. Add Digits
You receive a single non-negative integer num. Replace it with the sum of its base-10 digits, then do the same to the result, and keep going until only one digit is left. Return that final digit.
For instance, starting from 38: 3 + 8 = 11, then 1 + 1 = 2, and 2 is a single digit, so the answer is 2.
Once the loop version works, try to find the answer with no loop and no recursion at all — a closed-form O(1) formula exists.
Example 1:
Input: num = 38
Output: 2
Explanation: 38 → 3 + 8 = 11 → 1 + 1 = 2. One digit remains, so the answer is 2.
Example 2:
Input: num = 0
Output: 0
Explanation: 0 is already a single digit, so nothing needs to happen.
Constraints:
- 0 ≤ num ≤ 2³¹ - 1
Hints:
Simulate it directly: while the number has two or more digits, strip digits off with % 10 and / 10 and add them up. The value shrinks extremely fast, so this is already very cheap.
Sum-of-digits preserves the remainder mod 9 (because 10 ≡ 1 mod 9). So the answer is num mod 9 — except that a multiple of 9 must map to 9, not 0, and 0 itself stays 0. That is the digital root formula: 0 if num == 0, else 1 + (num − 1) % 9.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: num = 38
Expected output: 2