#7

Reverse Integer

MediumMathHas vizMath

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

Example 1

Input: x = 123

Output: 321

Digits reversed.

Example 2

Input: x = -123

Output: -321

Sign preserved.

Example 3

Input: x = 120

Output: 21

Trailing zero becomes a leading zero and is dropped.

Constraints

  • -2^31 <= x <= 2^31 - 1
Loading visualization…

Explanation

Reverse Integer is a Medium interview problem tagged [Math]. The winning approach is typically **Math**.

Intuition

Closed forms and sieves collapse search spaces.

Approach

Apply number-theory or constructive math (GCD, sieve, modular pow) instead of brute force.

  1. Identify math structure.
  2. Watch overflow/modulo.
  3. Prefer O(√n) or better when possible.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateMath

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n) or O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (Math), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #7 Reverse Integer as understood when the pattern clicks.