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
2
3
4
5
6
7
8
Input: x = 123
Output: 321

Input: x = -123
Output: -321

Input: x = 120
Output: 21

💡 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;

// check overflow before multiplying
if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && pop > 7))
return 0;
if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && pop < -8))
return 0;

rev = rev * 10 + pop;
}
return rev;
}
}

⏱️ 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.