LeetCode #7: Reverse Integer — Solved in Java
StringBuilder Flip and Digit-by-Digit Math
This problem asks you to reverse the digits of a 32-bit signed integer. If the result goes outside the allowed range, return 0. The minus sign stays attached and doesn't affect how the digits are handled.
One version uses string methods and is easy to read. The other works with math and avoids extra objects. Both handle edge cases. The second version keeps things closer to what the problem is really testing. Each one is broken down step by step so you can see how it works. The full text versions are at the bottom, ready to copy and run.
Given a signed 32-bit integer
x
, return its digits reversed. If reversing causes it to go out of the range[-2³¹, 2³¹ - 1]
, return0
.Example 1
Input:
x = 123
Output:321
Example 2
Input:
x = -123
Output:-321
Example 3
Input:
x = 120
Output:21
Constraint
-2³¹ <= x <= 2³¹ - 1
Solution 1 — StringBuilder Flip
This handles the reversal by turning the number into a string, flipping the digits, and then converting it back. It’s easy to write and read, which makes it a good choice when you're just trying to get something working. It also handles negatives and large numbers with very little code, but it leans on higher-level methods like parseInt
and StringBuilder
, which might not be ideal if you're being asked to manage data yourself.
Let’s go through it:
class Solution {
public int reverse(int x) {
This defines the class and the method. It takes a single integer as input.
boolean isNegative = x < 0;
We check if the number is negative and store that as a flag.
StringBuilder sb = new StringBuilder(Integer.toString(Math.abs(x)));
sb.reverse();
We convert the number to a string, take the absolute value, and reverse the characters using StringBuilder
.
try {
int reversed = Integer.parseInt(sb.toString());
We try to parse the reversed string back into an integer.
return isNegative ? -reversed : reversed;
} catch (NumberFormatException e) {
return 0;
}
If parsing fails because the value is out of bounds, we return 0
. Otherwise, we return the reversed number, adding the minus sign back if the original was negative.
}
}
We finish the method and return the final result.
This runs in O(n)
time, where n
is the number of digits in the input. It builds a reversed string using a StringBuilder
, and that takes up space proportional to the number of digits, so the space is also O(n)
. It’s simple and works well for small inputs, but it does use more memory and relies on exception handling to detect overflow.
Solution 2 — Digit-by-Digit Math
This version avoids converting the number to a string and works entirely with math. It goes digit by digit, pulling off the last number, shifting the result left, and adding it back. That lets you stay close to what the machine is actually doing, which is something interviewers tend to like. On top of that, the method checks for overflow at each step instead of relying on a final comparison or catching an error.
Let’s walk through it:
class Solution {
public int reverse(int x) {
This starts the method and takes the integer input.
int result = 0;
We use this to build the reversed number as we go.
while (x != 0) {
We loop through the number until there are no digits left.
int digit = x % 10;
x /= 10;
We grab the last digit with the modulo operator, then remove that digit from x
.
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && digit > 7)) {
return 0;
}
if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && digit < -8)) {
return 0;
}
Before we add anything to result
, we check if multiplying it by 10 would push it past the allowed 32-bit range. If it would, we return 0
right away.
result = result * 10 + digit;
If it's safe, we shift the digits over and add the new one.
}
return result;
}
After the loop finishes, we return the final reversed number.
This runs in O(n)
time, where n
is the number of digits in x
. Each digit is processed once, and we don't loop over anything more than we need to. Space is O(1)
because we don’t use any strings or collections, just a few variables to track the result and the digits. It’s compact, handles all edge cases, and gives you better control over what’s actually happening at each step.
StringBuilder Flip — Copy and Paste
class Solution {
public int reverse(int x) {
boolean isNegative = x < 0;
StringBuilder sb = new StringBuilder(Integer.toString(Math.abs(x)));
sb.reverse();
try {
int reversed = Integer.parseInt(sb.toString());
return isNegative ? -reversed : reversed;
} catch (NumberFormatException e) {
return 0;
}
}
}
Digit-by-Digit Math
class Solution {
public int reverse(int x) {
int result = 0;
while (x != 0) {
int digit = x % 10;
x /= 10;
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && digit > 7)) {
return 0;
}
if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && digit < -8)) {
return 0;
}
result = result * 10 + digit;
}
return result;
}
}