Reverse Integer — LeetCode 7 Python Solution
- Problem
- #7
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log |x|), where |x| is the absolute value of x |
| Space | O(1) auxiliary |
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
On a study list
This problem is on NeetCode 150.
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.