DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

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

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
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)