Add Digits

Given a non-negative integer num, keep replacing it with the sum of its digits until only one digit remains, and return that digit. Follow up: can you do it in O(1) time without any loop or recursion?

30:00

Add Digits
easy
Free written solution
Topics
Companies

Given a non-negative integer num, keep replacing it with the sum of its digits until only one digit remains, and return that digit. Follow up: can you do it in O(1) time without any loop or recursion?

Example 1:
Input: {"num":38}
Output: 2
Constraints:
  • 0≤num≤231−10 \leq \text{num} \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"num":38}

The slow way: keep adding the digits of 38 until one digit is left. Watch what stays the same.

repeated digit sums (the slow way)

3
8

already one digit

remainder class mod 9 (9 stands for remainder 0)

1

≡1

2

≡2

3

≡3

4

≡4

5

≡5

6

≡6

7

≡7

8

≡8

9

≡0

the O(1) shortcut

num == 0 ?
1 + (num - 1) % 9
Variables
VariableValue
num38
DepthFunction Call
Stack empty
0/8