7. Reverse Integer
🟧 Medium
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
Example 2
Input: x = -123 Output: -321
Example 3
Input: x = 120 Output: 21
Constraints
-2^31 <= x <= 2^31-1
Solution
My Solution (Basic Reversal)
Optimal Solution (Overflow Prevention)
Approach Analysis
This problem combines digit manipulation with careful overflow handling:
Basic Reversal (Your Solution):
Handle negative numbers separately
Build reversed number digit by digit
Check overflow at the end
Simple but may have edge cases
Overflow Prevention (Optimal):
Check overflow before each operation
Handle signs within main logic
More robust for edge cases
No extra space needed
Visualization of Both Approaches
Basic Reversal Process (Your Solution)
Overflow Prevention Process
Complexity Analysis
Basic Reversal (Your Solution)
Time: O(log₁₀|x|)
Process each digit once
Number of digits = log₁₀|x|
Simple arithmetic operations
Space: O(1)
Only use few variables
Constant extra space
No additional data structures
Overflow Prevention (Optimal)
Time: O(log₁₀|x|)
Same as basic solution
Extra overflow checks are O(1)
Still process each digit once
Space: O(1)
Only use result variable
Constant extra space
No temporary storage needed
Why Overflow Prevention Works
Mathematical Foundation:
MaxInt32 = 2147483647
MinInt32 = -2147483648
Last digits are 7 and -8
Division by 10 preserves sign
Early Detection:
Check before multiplication
Prevents any overflow
Handles all edge cases
No need for 64-bit integers
When to Use Each Approach
Basic Reversal When:
Learning number manipulation
Quick implementation needed
Input range is known safe
Code clarity is priority
Overflow Prevention When:
Production environment
Unknown input range
Performance critical
Memory constraints
Common Patterns & Applications
Related Problems:
String to Integer (atoi)
Palindrome Number
Add Two Numbers
Multiply Strings
Key Techniques:
Digit extraction
Overflow checking
Sign handling
Modular arithmetic
Interview Tips
Solution Highlights:
Handle signs properly
Check overflow early
Process digits efficiently
Consider all edge cases
Common Pitfalls:
Missing overflow check
Wrong sign handling
Integer division issues
Boundary conditions
Testing Strategy:
Positive numbers
Negative numbers
Zero
Maximum integers
Minimum integers
Follow-up Questions:
Handle decimal points?
Different base numbers?
Stream of digits?
Memory optimization?
Last updated
Was this helpful?