# LeetCode 7: Reverse Integer — Step-by-Step Visual Trace

**Medium** — Math | Integer Manipulation | Overflow Handling

## The 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, return 0.

## Approach

Extract digits from the input number one by one using modulo and integer division operations. Build the reversed number by multiplying the current result by 10 and adding each extracted digit, while checking for integer overflow before each multiplication.

**Time:** O(log n) · **Space:** O(1)

## Code

```python
class Solution:
    def reverse(self, x: int) -> int:
        INT_MAX = 2**31 - 1
        INT_MIN = -(2**31)

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

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

            if reversed_num > (INT_MAX - pop) // 10:
                return 0

            reversed_num = reversed_num * 10 + pop

        return reversed_num * sign
```

## Watch It Run

> **[Open interactive visualization](https://tracelit.dev/app?trace=0007_reverse-integer)**

> **Try it yourself:** Open [TraceLit](https://tracelit.dev/app?trace=0007_reverse-integer) and step through every line.

---

*Built with [TraceLit](https://tracelit.dev) — the visual algorithm tracer for LeetCode practice.*
