DevPath

← All problems

Add Digits (Digital Root)

Easy math

Description

Repeatedly add all digits until a single digit remains, and return it.

Constraints

0 <= n <= 2^31 - 1

Examples

Input: n = 38

Output: 2

3+8=11, 1+1=2

Hints (1)
  • The digital root is 1 + (n - 1) mod 9 when n > 0.

Solutions

Digital-root formula. · Time O(1) · Space O(1)

func addDigits(n int) int {
    if n == 0 {
        return 0
    }
    return 1 + (n-1)%9
}

Create a free account to submit solutions, track progress and save problems.

Create account