> ## 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.

# Reverse Integer Python Solution with Tests

> Tested Python solution for LeetCode 7 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 7, Medium. Topics: Math. [View on LeetCode](https://leetcode.com/problems/reverse-integer/description/).

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

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

## Problem

Given a signed 32-bit integer `x`, return `x` *with its digits reversed*. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-2^31, 2^31 - 1]`, then return `0`.

**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**

### Examples

```
Input: x = 123
Output: 321
```

```
Input: x = -123
Output: -321
```

```
Input: x = 120
Output: 21
```

### Constraints

* -2^31 \<= x \<= 2^31 - 1

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(log(x))
    # Space: O(1)
    def reverse(self, x: int) -> int:
        int_max = 2**31 - 1

        result = 0
        sign = 1 if x >= 0 else -1
        x = abs(x)

        while x != 0:
            digit = x % 10
            x //= 10

            # Check for overflow before adding the digit
            if result > (int_max - digit) // 10:
                return 0

            result = result * 10 + digit

        return sign * result
```

## Complexity

| Time      | Space |
| --------- | ----- |
| O(log(x)) | O(1)  |

## Tags

[Grind](/catalog/grind), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
