How to Reverse a Number in Java
The Challenge
Reverse the digits of a number - turn 123 into 321!
Solution
public class Main {
public static void main(String[] args) {
int number = 12345;
int reversed = 0;
while (number != 0) {
int digit = number % 10; // Get last digit
reversed = reversed * 10 + digit; // Add to reversed
number = number / 10; // Remove last digit
}
System.out.println("Reversed: " + reversed);
// Output: Reversed: 54321
}
}Step-by-Step Explanation
Let's reverse 123:
- Iteration 1: digit = 3, reversed = 3, number = 12
- Iteration 2: digit = 2, reversed = 32, number = 1
- Iteration 3: digit = 1, reversed = 321, number = 0
- Result: 321
Alternative: Using StringBuilder
int number = 12345;
String reversed = new StringBuilder(String.valueOf(number))
.reverse()
.toString();
int reversedNum = Integer.parseInt(reversed);
System.out.println("Reversed: " + reversedNum);
// Output: Reversed: 54321Did You Know?
Reversing a number is often used in palindrome checks! A number is a palindrome if it reads the same forwards and backwards (e.g., 121, 1331).
Watch Out!
Be careful with negative numbers! The algorithm above works for positive numbers. For negative numbers, handle the sign separately.
Real-World Use Cases
- Palindrome detection: Check if numbers read the same both ways
- Number puzzles: Mathematical games and challenges
- Data validation: Verify check digits
›Short versionOpen if you only have a minute.
- Peel the last digit with % 10, drop it with / 10, and append with reversed = reversed * 10 + digit.
- A numeric reverse drops trailing zeros: 120 becomes 21.
- reversed * 10 overflows int before the digit is added. Integer.MAX_VALUE reversed does not fit.
- The sign is a separate decision. A loop written as while (n > 0) never runs for a negative input.
Reverse a number
Build a number with digits in reverse order by peeling digits from right to left.
Working approach
- Extract the last digit with % 10 and remove it with / 10.
- Update reversed = reversed * 10 + digit on each step.
- Refuse the step when reversed > Integer.MAX_VALUE / 10, or accumulate in a long.
Walk the sample
- Input 123
- Digit 3 makes reversed 3
- Digit 2 makes reversed 32
- Digit 1 makes reversed 321
The trap
The multiply-by-ten step wraps. After the wrap, later digits are appended to a negative or otherwise meaningless value, and the method still returns it.
static int reverse(int n) {
if (n == Integer.MIN_VALUE) {
throw new ArithmeticException("reversed value does not fit in int");
}
int sign = n < 0 ? -1 : 1;
int value = Math.abs(n);
int reversed = 0;
while (value > 0) {
if (reversed > Integer.MAX_VALUE / 10) {
throw new ArithmeticException("reversed value does not fit in int");
}
reversed = reversed * 10 + value % 10;
value /= 10;
}
return sign * reversed;
}Why is the reverse of Integer.MAX_VALUE not an int?
2147483647 reversed is 7463847412, which is larger than Integer.MAX_VALUE.
Without a check before reversed * 10, the int wraps and the returned value is not the digit reversal.
Time O(d), space O(1), where d is the number of digits.
Easy to get wrong
- Forgetting value /= 10, which loops forever on a non-zero input.
- Using while (n > 0) and then wondering why negatives come back unchanged.