LeetCode 258. Add Digits

Post by ailswan Dec.12, 2023

258. Add Digits

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

  1. If the input num is less than or equal to 9, return num as it is a single-digit number.
  2. 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.
  3. 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)