Problem
Given an integernum, repeatedly add all its digits until the result has only one digit, and return it.
Examples
Constraints
0 <= num <= 2^31 - 1
O(1) runtime?
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 258 with 17 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 258 # by problem number
lcpy gen -s add_digits # by problem name
num, repeatedly add all its digits until the result has only one digit, and return it.
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.
Input: num = 0
Output: 0
0 <= num <= 2^31 - 1O(1) runtime?
class Solution:
# Time: O(1) (at most 3 passes for 32-bit inputs)
# Space: O(1)
def add_digits(self, num: int) -> int:
if num == 0:
return 0
return 1 + (num - 1) % 9
| Time | Space |
|---|---|
| O(1) (at most 3 passes for 32-bit inputs) | O(1) |