Reverse Integer - 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³¹, 2³¹ - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Input & Output

Example 1 — Basic Positive Number
$ Input: x = 123
Output: 321
💡 Note: Reverse the digits: 123 becomes 321. The result fits in 32-bit range so return 321.
Example 2 — Negative Number
$ Input: x = -123
Output: -321
💡 Note: Reverse the digits while preserving the negative sign: -123 becomes -321.
Example 3 — Overflow Case
$ Input: x = 1534236469
Output: 0
💡 Note: Reversing gives 9646324351, which exceeds 2³¹-1 = 2147483647, so return 0.

Constraints

  • -2³¹ ≤ x ≤ 2³¹ - 1

Visualization

Tap to expand
Reverse Integer - Optimal Solution INPUT Signed 32-bit Integer x = 123 1 2 3 100s 10s 1s Constraints: Range: [-2^31, 2^31 - 1] Min: -2,147,483,648 Max: 2,147,483,647 No 64-bit storage ALGORITHM STEPS 1 Initialize result = 0 Store reversed number 2 Extract last digit digit = x % 10 3 Check overflow Before: result*10 + digit 4 Build result result = result*10 + digit Iterations for x=123: i=1: 123%10=3, res=3 i=2: 12%10=2, res=32 i=3: 1%10=1, res=321 x=0, loop ends FINAL RESULT Reversed Integer 3 2 1 100s 10s 1s 321 Verification: Input: 123 Output: 321 Status: OK (in range) Key Insight: Check overflow BEFORE multiplying by 10. Compare result with INT_MAX/10 (214748364). If result > INT_MAX/10 OR (result == INT_MAX/10 AND digit > 7), return 0. Time: O(log n), Space: O(1). TutorialsPoint - Reverse Integer | Optimal Solution
Asked in
Apple 15 Amazon 12 Bloomberg 8 Microsoft 6
329.3K Views
High Frequency
~15 min Avg. Time
8.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen