Skip to main content

7. Reverse Integer

medium

Reverse the digits of a 32-bit signed integer, returning 0 if the reversed value overflows. The textbook overflow-aware arithmetic problem — tests both modular digit math and bounds discipline.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

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

Constraints

  • -2^31 <= x <= 2^31 - 1

Examples

Example 1

Input
x = 123
Output
321

Example 2

Input
x = -123
Output
-321

Example 3

Input
x = 120
Output
21

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Peel digits with x % 10 and shift the running result with result * 10 + digit. Modulo preserves sign in most languages, so negatives largely take care of themselves.

Hint 2

The catch is the constraint: no 64-bit ints. You must detect overflow BEFORE multiplying by 10.

Hint 3

Before doing result = result * 10 + digit, check: if result > INT_MAX/10 or (result == INT_MAX/10 and digit > 7), it will overflow positive. Mirror for negatives with INT_MIN/10 and -8.

Hint 4

On overflow, return 0 immediately.

Solution approach

Reveal approach

Pop digits one at a time: digit = x % 10, x /= 10. Build result = result * 10 + digit. Before each multiplication, guard against overflow: if result > INT_MAX/10 (214748364) the next *10 overflows; if result == INT_MAX/10 and the next digit > 7, the final value exceeds INT_MAX. Mirror logic for negatives using INT_MIN/10 (-214748364) and digit < -8. Return 0 on overflow detection. Stop when x reaches 0. O(log10(x)) time, O(1) space. This pre-multiplication overflow check is the standard interview answer when 64-bit ints are forbidden.

Complexity

Time
O(log n)
Space
O(1)

Related patterns

  • math

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Apple
  • Bloomberg
  • Adobe

Practice these live with InterviewChamp.AI

Drill Reverse Integer and Math problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →