MediumNo. 0007

Reverse Integer — LeetCode 7 Python Solution

Topics
Math
On a study list
NeetCode 150
Reading time
2 min

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 [-231, 231 - 1], then return 0.

Example

Input
x = 123
Output
321

Python solution

PythonSolution
class Solution:
    def reverse(self, x: int) -> int:
        ans = 0
        mi, mx = -(2**31), 2**31 - 1
        while x:
            if ans < mi // 10 + 1 or ans > mx // 10:
                return 0
            y = x % 10
            if x < 0 and y > 0:
                y -= 10
            ans = ans * 10 + y
            x = (x - y) // 10
        return ans

Complexity

Time
O(log |x|), where |x| is the absolute value of x
Space · auxiliary
O(1)

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 7. Reverse Integer is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0009Palindrome NumberEasy
0002Add Two NumbersMedium
0043Multiply StringsMedium
0048Rotate ImageMedium
0050Pow(x, n)Medium
0060Permutation SequenceHard

Frequently asked questions

How hard is LeetCode 7. Reverse Integer?

LeetCode 7. Reverse Integer is rated Medium on LeetCode.

What is the time complexity of LeetCode 7. Reverse Integer?

The Python solution on this page runs in O(log |x|), where |x| is the absolute value of x.

What is the space complexity of LeetCode 7. Reverse Integer?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 7. Reverse Integer cover?

LeetCode 7. Reverse Integer is tagged Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.