Reverse a Number in Java: Solution, Explanation & Practice
Reverse the digits of an integer
Problem summary
Write a program that reverses the digits of a given number. Your code should work for ANY positive integer.
Starter code
public class Main {
public static void main(String[] args) {
int number = 12345; // Test case 1
// Write code to reverse the number
// Should work for ANY number
// Print: Reversed: <result>
}
}Expected output and test cases
- 12345 → 54321
Reversed: 54321
- 1234 → 4321
Reversed: 4321
- 1 → 1
Reversed: 1
Hints
- Build the reversed number digit by digit
- Use modulus to get last digit, divide to remove it
- Multiply result by 10 before adding each digit
Validated solution
Reveal Java solution
public class Main {
static int reverse(int value) {
int result = 0;
while (value != 0) {
int digit = value % 10;
result = result * 10 + digit;
value /= 10;
}
return result;
}
public static void main(String[] args) {
System.out.println("Reversed: " + reverse(12345));
}
}How to approach the problem
Build the answer from left to right by moving the accumulated result one decimal place before adding the current last digit. Leading zeroes in the reversed representation naturally disappear because an int has no leading-zero notation.
Approach
- Extract the final digit with modulus.
- Shift the partial answer with result * 10.
- Remove the processed digit using integer division.
Time and space complexity
Time: O(d). Space: O(1).
Edge cases to test
- A value ending in zero, such as 120, reverses to 21.
- A reversed int can overflow even when the original int fits.
Common mistakes
- Updating value before saving its last digit.
- Using a String reversal when the aim is arithmetic practice without documenting that choice.
Follow-up challenge
Detect reverse overflow and return an OptionalInt instead of a wrapped result.
Related Core Java Basics exercises
Practice all Core Java Basics exercises · Run this idea in the Java compiler