Digital Root

258.Add Digits

Math

Problem Statement:

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. This is also known as calculating the digital root.

Example:

Input:

num = 38

Output:

2

Java Solution:

// Stupid math problem "Digital Root"
public int addDigits(int num) {
    if (num == 0) return 0;
    if (num % 9 == 0) return 9;
    return num % 9;
}

Python Solution:

def addDigits(self, num: int) -> int:
    if num == 0: return 0
    if num % 9 == 0: return 9
    return num % 9

C++ Solution:

class Solution {
public:
    int addDigits(int num) {
        if(num == 0) return 0;
        if(num % 9 == 0) return 9;
        return num % 9;
    }
};

Explanation:

This is a mathematical solution based on the concept of digital root: 1. If number is 0, return 0 2. If number is divisible by 9, return 9 3. Otherwise, return remainder when divided by 9

Complexity:

Time: O(1) | Space: O(1)

Previous
Previous

Diameter of Binary Tree

Next
Next

Common factors