How to Reverse an Integer in Java: Solving the LeetCode Question
If you’re diving into the world of programming, chances are you’ll come across algorithmic challenges like the “Reverse Integer” problem on LeetCode. This problem might seem intimidating at first, but fear not! In this blog, we’ll break it down in simple terms and provide a step-by-step guide on how to reverse an integer in Java.
Understanding the Problem
The “Reverse Integer” problem on LeetCode asks you to reverse an integer. Sounds easy, right? Well, there’s a catch. You must consider some edge cases and constraints:
- Input: You’ll receive a 32-bit signed integer. This means the range of integers you need to handle is from -2^31 to 2^31 – 1.
- Output: Your function should return 0 if the reversed integer overflows. In other words, if the result is not within the 32-bit signed integer range, return 0.
Approach 1: Using Strings
One straightforward approach to reversing an integer is to convert it to a string, reverse the string, and then convert it back to an integer. Here’s how you can do it in Java:
public int reverse(int x) {
// Convert the integer to a string
String str = Integer.toString(x);
// Handle negative numbers by separating the sign
StringBuilder reversedStr = new StringBuilder();
if (x < 0) {
reversedStr.append("-");
str = str.substring(1); // Remove the negative sign
}
// Reverse the string
for (int i = str.length() - 1; i >= 0; i--) {
reversedStr.append(str.charAt(i));
}
// Convert the reversed string back to an integer
try {
return Integer.parseInt(reversedStr.toString());
} catch (NumberFormatException e) {
return 0; // Handle integer overflow
}
}
Let’s break down the code:
- We start by converting the input integer
x
into a stringstr
. This makes it easier to manipulate each digit. - If the input integer is negative, we handle it separately by appending a ‘-‘ sign to the
reversedStr
and removing the negative sign fromstr
. - We iterate through the characters in
str
from the end to the beginning and append each character toreversedStr
, effectively reversing the string. - Finally, we attempt to parse
reversedStr
back into an integer. If this operation throws aNumberFormatException
, it means we’ve encountered an overflow, and we return 0.
Let’s see how this approach performs with some examples:
- Input:
123
- Output:
321
- Input:
-123
- Output:
-321
- Input:
120
- Output:
21
- Input:
1534236469
- Output:
0
(Overflow)
This approach is simple to understand, but it involves string manipulation, which might not be the most efficient solution.
Approach 2: Using Arithmetic Operations
A more efficient approach to reverse an integer is to use arithmetic operations. Here’s how you can do it:
public int reverse(int x) {
int reversed = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
// Check for integer overflow
if (reversed > Integer.MAX_VALUE / 10 || (reversed == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (reversed < Integer.MIN_VALUE / 10 || (reversed == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
reversed = reversed * 10 + pop;
}
return reversed;
}
Let’s break down this approach:
- We initialize
reversed
to 0, which will store the reversed integer. - We enter a
while
loop that continues untilx
becomes 0. - Inside the loop, we calculate
pop
as the last digit ofx
using the modulo operator (%
). We also updatex
by removing the last digit using integer division (/
). - To handle integer overflow, we check if
reversed
will exceed theInteger.MAX_VALUE
orInteger.MIN_VALUE
bounds when multiplied by 10 and added topop
. If it does, we return 0 to indicate an overflow. - Otherwise, we update
reversed
by multiplying it by 10 and addingpop
, effectively reversing the digits.
Let’s see how this approach performs with the same examples:
- Input:
123
- Output:
321
- Input:
-123
- Output:
-321
- Input:
120
- Output:
21
- Input:
1534236469
- Output:
0
(Overflow)
This approach is more efficient than the string manipulation approach, and it handles overflows correctly.
Comparing the Two Approaches
Now that we’ve explored both approaches, let’s compare them in terms of time complexity and space complexity:
Approach 1 (Using Strings)
- Time Complexity: O(log(x)) – where x is the input integer. This is because we are converting the integer to a string and then iterating through its digits.
- Space Complexity: O(log(x)) – the space used for the string representation of the integer.
Approach 2 (Using Arithmetic Operations)
- Time Complexity: O(log(x)) – the same as the previous approach, as we are also processing each digit of the integer.
- Space Complexity: O(1) – we only use a few extra variables, regardless of the size of the input integer.
As you can see, the second approach is more efficient in terms of space complexity and is generally preferred for solving the “Reverse Integer” problem on LeetCode.
Conclusion
Solving algorithmic problems like reversing an integer is an essential skill for any programmer. In this blog, we’ve explored two approaches to reverse an integer in Java, using both string manipulation and arithmetic operations. The second approach, which uses arithmetic operations, is more efficient and handles integer overflow correctly.
Remember that when tackling coding challenges, understanding the problem, considering edge cases, and optimizing your solution are key to success. Practice makes perfect, so keep honing your coding skills by attempting more algorithmic problems on platforms like LeetCode, and you’ll become a proficient programmer in no time.
Happy coding!
Read More –
94. Binary Tree Inorder Traversal | Binary Tree Inorder Traversal LeetCode Solution in Java – https://kamleshsingad.com/94-binary-tree-inorder-traversal-binary-tree-inorder-traversal-leetcode-solution-in-java/
589. N-ary Tree Preorder Traversal | N-ary Tree Preorder Traversal LeetCode Solution in Java – https://kamleshsingad.com/589-n-ary-tree-preorder-traversal-n-ary-tree-preorder-traversal-leetcode-solution-in-java/
09. Palindrome Number LeetCode Solution in Java – Check if a Number is a Palindrome or Not – https://kamleshsingad.com/what-is-palindrome-number-leetcode-solution-in-java-check/