Java Program to Reverse a Number with Output and Explanation
num % 10, build the reversed number by reversed = reversed * 10 + digit, and reduce the original number by num = num / 10 until it becomes zero.Examples
How to Think About It
%. Then, add that digit to a new number that grows by shifting digits left (multiplying by 10). Keep doing this until the original number is fully processed (becomes zero).Algorithm
Code
public class ReverseNumber { public static void main(String[] args) { int num = 1234; int reversed = 0; while (num != 0) { int digit = num % 10; reversed = reversed * 10 + digit; num /= 10; } System.out.println(reversed); } }
Dry Run
Let's trace the number 1234 through the code to see how it reverses.
Initial values
num = 1234, reversed = 0
First loop iteration
digit = 1234 % 10 = 4; reversed = 0 * 10 + 4 = 4; num = 1234 / 10 = 123
Second loop iteration
digit = 123 % 10 = 3; reversed = 4 * 10 + 3 = 43; num = 123 / 10 = 12
Third loop iteration
digit = 12 % 10 = 2; reversed = 43 * 10 + 2 = 432; num = 12 / 10 = 1
Fourth loop iteration
digit = 1 % 10 = 1; reversed = 432 * 10 + 1 = 4321; num = 1 / 10 = 0
Loop ends
num is now 0, loop stops, reversed = 4321
| num | digit | reversed |
|---|---|---|
| 1234 | 4 | 4 |
| 123 | 3 | 43 |
| 12 | 2 | 432 |
| 1 | 1 | 4321 |
Why This Works
Step 1: Extract last digit
Using num % 10 gets the last digit of the number, like peeling one digit off.
Step 2: Build reversed number
Multiply the current reversed number by 10 to shift digits left, then add the extracted digit.
Step 3: Remove last digit
Divide the original number by 10 using integer division to drop the last digit and repeat.
Alternative Approaches
public class ReverseNumber { public static void main(String[] args) { int num = 1234; String str = Integer.toString(num); String reversedStr = new StringBuilder(str).reverse().toString(); int reversed = Integer.parseInt(reversedStr); System.out.println(reversed); } }
public class ReverseNumber { public static int reverse(int num, int reversed) { if (num == 0) return reversed; return reverse(num / 10, reversed * 10 + num % 10); } public static void main(String[] args) { int num = 1234; System.out.println(reverse(num, 0)); } }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time depends on the number of digits d.
Space Complexity
Uses only a few integer variables, so space is constant O(1).
Which Approach is Fastest?
The loop method is fastest and uses least memory; string conversion is simpler but slower; recursion uses more stack space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop method | O(d) | O(1) | Efficient and simple |
| String conversion | O(d) | O(d) | Quick coding, less efficient |
| Recursive method | O(d) | O(d) | Elegant but uses stack memory |
/ to remove the last digit after extracting it with modulo.