TGViewer
Python | LeetCode Python | LeetCode @easy_python_task · 9.03K subscribers
Post #2139 1.26K
Задача: 258. Add Digits
Сложность: easy

Дано целое число num. Повторно складывайте все его цифры, пока результат не станет однозначным, и верните его.

Пример:
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.


👨‍💻 Алгоритм:

1️⃣Инициализируйте переменную digital_root значением 0.

2️⃣В цикле, пока num больше 0:
Добавьте к digital_root последнюю цифру num.
Уменьшите num, удалив последнюю цифру.
Если num равно 0 и digital_root больше 9, присвойте num значение digital_root и сбросьте digital_root в 0.

3️⃣Верните значение digital_root.

😎 Решение:
class Solution:
def addDigits(self, num: int) -> int:
digital_root = 0
while num > 0:
digital_root += num % 10
num //= 10
if num == 0 and digital_root > 9:
num = digital_root
digital_root = 0
return digital_root


Ставь 👍 и забирай 📚 Базу знаний
  • 🔥 3
More from @easy_python_task
  1. Oct 12, 2026Задача: 104. Maximum Depth of Binary Tree Сложность: easy Дан корень бинарного дерева, вер…
  2. Oct 11, 2026Post #2439
  3. Oct 11, 2026Задача: 997. Find the Town Judge Сложность: easy В городе есть n человек, помеченных от 1…
  4. Oct 11, 2026Post #2437
  5. Oct 11, 2026Задача: 436. Find Right Interval Сложность: medium Дан массив интервалов, где intervals[i]…
  6. Oct 10, 2026Задача: 1249. Minimum Remove to Make Valid Parentheses Сложность: medium Дана строка s из…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →