258. Add Digits
Math, Number Theory, Simulation ·Problem Statement
link: https://leetcode.com/problems/add-digits/ https://leetcode.cn/problems/add-digits/
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Example:
Input: num = 38
Output: 2
Input: num = 0
Output: 0
Solution Approach
To find the digital root of a number, repeatedly add its digits until the result has only one digit.
Algorithm
- If the input num is less than or equal to 9, return num as it is a single-digit number.
- Initialize a variable tmp to 0. Iterate through the digits of num by adding the last digit to tmp and updating num until it becomes 0.
- Recursively call the addDigits function with the updated value of tmp until a single-digit result is obtained.
Implement
class Solution:
def addDigits(self, num: int) -> int:
if num <= 9:
return num
tmp = 0
while num > 0:
tmp += num % 10
num //= 10
return self.addDigits(tmp)