Java – Reverse a Number
To reverse a number in Java, take its digits from right to left and build a new number in the opposite order. For example, reversing 12345 gives 54321.
The usual arithmetic approach repeatedly gets the last digit using the remainder operator % 10, appends that digit to the reversed value, and removes the last digit using integer division by 10.
digit = number % 10;
reverse = reverse * 10 + digit;
number = number / 10;
You can implement this logic with a while loop or a for loop. If the number is first represented as text, Java’s StringBuilder.reverse() method provides another approach.
Following picture presents a sample input and output for the Java Program – Reverse a Number.
How the Arithmetic Logic Reverses Each Digit
Suppose the number is 1234. The expression 1234 % 10 gives 4, which is the last digit. Integer division 1234 / 10 gives 123, effectively removing that last digit. Repeating these two operations processes every digit.
The reversed value is built with reverse = reverse * 10 + digit. Starting with reverse = 0, the intermediate values for 1234 are 4, 43, 432, and finally 4321.
Example 1 – Reverse Number using While Loop
In this example, we shall reverse a number using Java While Loop.
Following algorithm will be used to reverse a number.
Algorithm for Reversing a Number with a While Loop
- Start.
- Take number in a variable
n. - Take another variable named
reverse, to store the reversed number. - Check if
nis not zero. - If the above condition is true, take the last digit of
nand append it toreverse. - Pop out the last digit of
n. Go to step 4. - Stop.
Java Program
/**
* Java Program - Reverse Number
*/
public class Factorial {
public static void main(String[] args) {
//number
int n = 123456789;
//variable to hold reversed number
int reverse = 0;
//reverse n
while(n!=0) {
reverse = (reverse * 10) + n%10; //append last digit of n to reverse
n /= 10; //pop last digit of n
}
System.out.println(reverse);
}
}
Run the above program. After the execution of while loop, reverse contains the reversed number.
987654321
The loop continues until n becomes 0. Each iteration moves one digit from n to the end of reverse.
Example 2 – Reverse Number using For Loop
In this example, we shall use Java For Loop to reverse the given number. We will use the same algorithm as in the above example.
Java Program
/**
* Java Program - Reverse Number
*/
public class ReverseNumber {
public static void main(String[] args) {
//number
int n = 123456789;
//variable to hold reversed number
int reverse = 0;
//reverse n
for(; n!=0; n/=10)
reverse = (reverse * 10) + n%10;
System.out.println(reverse);
}
}
Run the above Java program, and you will get the following output in console.
987654321
Here, the for loop has no initialization expression. The condition is n != 0, and n /= 10 removes one digit after every iteration.
Reverse a Number in Java Using Scanner Input
When the number should be entered at runtime, use Scanner to read the integer and apply the same remainder-and-division logic.
import java.util.Scanner;
public class ReverseNumberInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int reverse = 0;
while (number != 0) {
int digit = number % 10;
reverse = reverse * 10 + digit;
number /= 10;
}
System.out.println("Reversed number: " + reverse);
scanner.close();
}
}
For an input of 2468, the program produces:
Enter a number: 2468
Reversed number: 8642
Example 3 – Reverse Number using StringBuilder.reverse()
In this example, we shall use StringBuilder class and its reverse method to reverse a number.
Algorithm for Reversing a Number with StringBuilder.reverse()
Following algorithm is used to reverse a number.
- Start.
- The the number in a variable
n. - Take another variable reverse, where we shall store reversed number.
- Conver n to string by type casting.
n+"". - Create a new StringBuilder() object with the string formed in the above step.
- Call reverse() method on the StringBuilder object.
- Call toString() method on the StringBuilder object. toString() returns a reversed string.
- Convert the reversed string to integer using Integer.parseInt().
- Stop.
Java Program
/**
* Java Program - Reverse Number
*/
public class ReverseNumber {
public static void main(String[] args) {
//number
int n = 123456789;
//reverse number
int reverse = Integer.parseInt((new StringBuilder(n+"")).reverse().toString());
System.out.println(reverse);
}
}
Run the above program. The number is reversed.
987654321
StringBuilder has a reverse() method for character sequences; primitive integer types such as int do not have a built-in reverse() method. This approach therefore converts the number to text first and converts the reversed text back to an integer.
Reverse a Number in Java Without an Explicit Loop
If you do not want to write a loop explicitly, you can convert a positive integer to a string, reverse the characters with StringBuilder, and parse the result.
public class ReverseWithoutLoop {
public static void main(String[] args) {
int number = 4567;
String reversedText = new StringBuilder(String.valueOf(number))
.reverse()
.toString();
int reversedNumber = Integer.parseInt(reversedText);
System.out.println(reversedNumber);
}
}
Output
7654
This version is suitable for non-negative integers. A negative sign needs separate handling because simply reversing -123 produces the text 321-, which cannot be parsed as an integer.
Reverse a Negative Number in Java
The arithmetic loop can also reverse negative integers because Java’s remainder and integer-division operations preserve the sign during the calculation. For example, -1234 can be reversed to -4321.
public class ReverseNegativeNumber {
public static void main(String[] args) {
int number = -1234;
int reverse = 0;
while (number != 0) {
int digit = number % 10;
reverse = reverse * 10 + digit;
number /= 10;
}
System.out.println(reverse);
}
}
Output
-4321
What Happens to Trailing Zeros When a Number Is Reversed
Leading zeros are not stored in an integer. Therefore, if the original number ends in one or more zeros, those zeros disappear after the number is reversed. For example, reversing 1200 as an integer gives 21, not 0021.
If those zeros must be preserved for display, treat the input as a string instead of converting the reversed result to an integer.
public class ReversePreserveZeros {
public static void main(String[] args) {
String number = "1200";
String reversed = new StringBuilder(number).reverse().toString();
System.out.println(reversed);
}
}
Output
0021
Prevent Integer Overflow While Reversing a Number
A reversed value may be outside the range of Java’s int type even when the original number fits in an int. The multiplication in reverse * 10 + digit can therefore overflow for sufficiently large values.
One straightforward option is to perform the calculation with long and check whether the result still falls within the int range before casting it back.
public class ReverseWithOverflowCheck {
public static void main(String[] args) {
int number = 1534236469;
int original = number;
long reverse = 0;
while (number != 0) {
reverse = reverse * 10 + number % 10;
number /= 10;
}
if (reverse < Integer.MIN_VALUE || reverse > Integer.MAX_VALUE) {
System.out.println("Reversed value is outside the int range.");
} else {
System.out.println((int) reverse);
}
}
}
This distinction matters when the input is not restricted to values whose reversed form is known to fit in an int.
Time and Space Complexity of Reversing an Integer
For the arithmetic loop, one digit is processed during each iteration. If the number contains d digits, the loop performs d iterations, giving a time complexity of O(d). It uses only a fixed number of numeric variables, so its auxiliary space complexity is O(1).
The StringBuilder approach also processes the digits, but it creates a string representation and a mutable character sequence, so it requires additional space proportional to the number of characters.
Java Number Reversal: Key Points
- Use
number % 10to extract the last digit. - Use
reverse * 10 + digitto append a digit to the reversed number. - Use
number / 10to remove the last digit. - A
whileloop and aforloop can implement the same arithmetic algorithm. StringBuilder.reverse()reverses characters, so an integer must first be converted to a string.- Trailing zeros disappear when the reversed result is stored as an integer.
- Check for overflow if reversing arbitrary
intvalues.
Conclusion – Reverse a Number in Java
In this Java Tutorial, we learned how to reverse a number using Looping techniques and StringBuilder class.
For numeric processing, the remainder-and-division approach is usually the most direct: extract the last digit with % 10, append it to the reversed value, and remove the processed digit with / 10. For text-oriented input or when leading zeros in the reversed representation must be retained, reversing a string is more appropriate.
TutorialKart.com