Algorithm Day103 - Reverse Integer
🧩 Problem Description
LeetCode 7 - Reverse Integer
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], return 0.
Example:
1 | Input: x = 123 |
💡 First Thought (Convert to String)
The simplest way is to convert the number to a string, reverse it, and parse it back.
However, this is not efficient and requires handling signs and overflow carefully.
⚙️ Optimized Approach — Math Manipulation
We can extract digits using modulo and build the reversed number step by step.
Java Code
1 | public class Solution { |
⏱️ Complexity Analysis
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Reverse digits | O(log₁₀(n)) | O(1) |
🧠 Key Takeaways
- Always check overflow/underflow before multiplication.
- String reversal is simple but not optimal for integer manipulation.
- The mathematical approach avoids unnecessary conversions.
📘 Next Step: We’ll explore more number-based manipulation problems next.