7. Reverse Integer
mediumReverse 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 Sam K., 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
x = 123321Example 2
x = -123-321Example 3
x = 12021Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
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
More Math practice problems
- 8. String to Integer (atoi)
- 9. Palindrome Number
- 12. Integer to Roman
- 13. Roman to Integer
- 29. Divide Two Integers
- 38. Count and Say
- 43. Multiply Strings
- 50. Pow(x, n)