> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Add Digits Python Solution with Tests

> Tested Python solution for LeetCode 258 with 17 pytest cases. Generate a practice environment with lcpy.

LeetCode 258, [Easy](/catalog/easy). Topics: [Math](/catalog/topics/math), [Simulation](/catalog/topics/simulation), [Number Theory](/catalog/topics/number-theory). [View on LeetCode](https://leetcode.com/problems/add-digits/description/).

Generate this problem as a practice environment: tested reference solution, 17 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 258   # by problem number
lcpy gen -s add_digits   # by problem name
```

## Problem

Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.

### Examples

```
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
```

### Constraints

* `0 <= num <= 2^31 - 1`

**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/add_digits/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/add_digits/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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
```

## Complexity

| Time | Space |
| - | - |
| O(1) (at most 3 passes for 32-bit inputs) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.