Java Program to Reverse Number Using While Loop
digit = number % 10, build the reversed number with reversed = reversed * 10 + digit, and reduce the original number by number = number / 10 until it becomes zero.Examples
How to Think About It
%. Then, add each digit to a new number by shifting the existing digits left (multiply by 10) and adding the new digit. Keep doing this until the original number has no digits left.Algorithm
Code
public class ReverseNumber { public static void main(String[] args) { int number = 1234; int reversed = 0; while (number > 0) { int digit = number % 10; reversed = reversed * 10 + digit; number = number / 10; } System.out.println(reversed); } }
Dry Run
Let's trace the number 1234 through the code to see how it reverses.
Initial values
number = 1234, reversed = 0
First loop iteration
digit = 1234 % 10 = 4; reversed = 0 * 10 + 4 = 4; number = 1234 / 10 = 123
Second loop iteration
digit = 123 % 10 = 3; reversed = 4 * 10 + 3 = 43; number = 123 / 10 = 12
Third loop iteration
digit = 12 % 10 = 2; reversed = 43 * 10 + 2 = 432; number = 12 / 10 = 1
Fourth loop iteration
digit = 1 % 10 = 1; reversed = 432 * 10 + 1 = 4321; number = 1 / 10 = 0
Loop ends
number is now 0, loop stops, reversed number is 4321
| number | digit | reversed |
|---|---|---|
| 1234 | 4 | 4 |
| 123 | 3 | 43 |
| 12 | 2 | 432 |
| 1 | 1 | 4321 |
Why This Works
Step 1: Extract last digit
Using number % 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 new digit to append it.
Step 3: Remove last digit
Divide the original number by 10 to remove the last digit and prepare for the next iteration.
Alternative Approaches
public class ReverseNumber { public static void main(String[] args) { int number = 1234; String str = Integer.toString(number); String reversedStr = new StringBuilder(str).reverse().toString(); int reversed = Integer.parseInt(reversedStr); System.out.println(reversed); } }
public class ReverseNumber { public static int reverse(int number, int reversed) { if (number == 0) return reversed; return reverse(number / 10, reversed * 10 + number % 10); } public static void main(String[] args) { int number = 1234; System.out.println(reverse(number, 0)); } }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time grows linearly with the number of digits.
Space Complexity
Only a few integer variables are used, so space is constant regardless of input size.
Which Approach is Fastest?
The while loop method is fastest and most memory efficient compared to string conversion or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| While Loop | O(d) | O(1) | Efficient numeric reversal |
| String Conversion | O(d) | O(d) | Simplicity, small inputs |
| Recursion | O(d) | O(d) | Elegant code, small inputs |