Reverse a Number in Java
Problem
Reversing a number's digits means rebuilding it with the last digit first, by peeling digits off one end and appending them onto a new running value.
Given a number, reverse the order of its digits.
Java Program
public class ReverseNumber {
public static void main(String[] args) {
int n = 1234;
int reversed = 0;
while (n > 0) {
reversed = reversed * 10 + n % 10; // shift left and append the last digit
n /= 10;
}
System.out.println("Reversed number: " + reversed);
}
}Output
Core Logic
Shifting the running result one place left and appending the next extracted digit rebuilds the number with its digits in reverse order.
- 1
n % 10extracts the current last digit ofn. - 2
reversed * 10 + digitshifts every digit already inreversedone place left, then appends the newly extracted digit. - 3
n /= 10removes the digit just processed, and the loop continues untilnreaches0.
1234, the digits 4, 3, 2, 1 are extracted in that order and appended in turn, building reversed up to 4321.Key Point: Each digit is appended in the exact order it's extracted — since digits come off from the end first, appending them in that order naturally reverses the whole number.
Why: Each loop iteration strips one digit off n and appends it to the running result, so the number of iterations equals n's digit count d.
Key Concepts
Approach 2: Using StringBuilder.reverse()
public class ReverseNumberStringBuilder {
public static void main(String[] args) {
int n = 1234;
// Reverses the digits via a String instead of arithmetic
int reversed = Integer.parseInt(new StringBuilder(String.valueOf(n)).reverse().toString());
System.out.println("Reversed number: " + reversed);
}
}
Output
Core Logic
Converting the number to a String and reversing it with the built-in StringBuilder.reverse() skips the manual digit-by-digit arithmetic entirely.
- 1
String.valueOf(n)converts the number into its digit string. - 2
new StringBuilder(...).reverse()flips the digit string's order in place. - 3
Integer.parseInt(...)converts the reversed string back into anint.
1234, new StringBuilder("1234").reverse().toString() gives "4321", parsed back into the same 4321 the manual version computes.Key Point: This is a matter of style, not efficiency — the StringBuilder version reads a bit more directly at the cost of allocating a small String and buffer, where the arithmetic version works with just primitives.
Why: Reversing through a String still visits each of the d digits once, but this version allocates a String and StringBuilder buffer proportional to the digit count, unlike the arithmetic version's constant space.