Add Digits

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Follow up: Could you do it without any loop/recursion in O(1) runtime?

Example 1
Inputnum = 38
Output2
The process is 38 --> 3 + 8 --> 11, then 11 --> 1 + 1 --> 2, and since 2 has only one digit, return it.
Example 2
Inputnum = 0
Output0
The number 0 already has only one digit, so return 0.

Constraints

  • 0 <= num <= 2^31 - 1

Asked at 10 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate