Table of Contents
ToggleIn this article, we will see how to reverse a number in Java.
Let’s dive in.
Problem Statement
Reversing a number means swapping the digits. To Reverse a number we convert a number from its original form to a form where its digits are in the opposite order.
For Example:
Input:
96724
Output:
42769
Solution
We will see three different ways to reverse a number in Java. Those are:
- Using Loops
- Using Recursion
- Using StringBuilder
Approach 1: Using Loops
Let’s check how to reverse a number in java using loops
Algorithm
You can represent any number by using the format 10*a+b, and we will utilize this representation to reverse a number.
- Begin with your original number (
num
). - Initialise an empty result variable (
rev = 0
). - Until
num
is not0
:- Extract the last digit of ‘num’ using the modulo operator (num % 10).
- To form rev we will use 10*a+b
- So, Multiply
rev
by10
and add the last digit obtained torev
. - Divide
num
by10
(discard the remainder) to move to the next digit.
- Once
num
is0
,rev
will have the reversed number.
Java Program To Reverse A Number Using Loops
// Java Program To Reverse A Number Using Loops
public class ReverseNumber {
public static void main(String[] args) {
int num = 12345; // Replace this with the number you want to reverse
int rev = 0;
while (num != 0) {
int digit = num % 10; // Extract the last digit
rev = rev * 10 + digit; // Add the digit to the reversed number
num /= 10; // Remove the last digit
}
System.out.println("Reversed Number: " + rev);
}
}
Output
Reversed Number: 54321
Code Explanation
Step | num | rev | Action |
---|---|---|---|
1 | 12345 | 0 | Initialize num and rev . |
2 | 12345 | 5 | Extract last digit (12345 % 10 = 5). Add the digit to the reversed number (0*10 + 5) |
1234 | 5 | Remove last digit (num /= 10). | |
3 | 1234 | 54 | Extract last digit (1234 % 10 = 4). Add the digit to the reversed number (5*10 + 4) |
123 | 54 | Remove last digit (num /= 10). | |
4 | 123 | 543 | Extract last digit (123 % 10 = 3). Add the digit to the reversed number (54*10 + 3) |
12 | 543 | Remove last digit (num /= 10). | |
5 | 12 | 5432 | Extract last digit (12 % 10 = 2). Add the digit to the reversed number (543*10 + 2) |
1 | 5432 | Remove last digit (num /= 10). | |
6 | 1 | 54321 | Extract last digit (1 % 10 = 1). Add the digit to the reversed number (5432*10 + 1) |
0 | 54321 | Remove last digit (num /= 10). | |
7 | 0 | 54321 | The loop exits since num is now 0. |
At the end of the program, rev
contains the reversed number, which is 54321.
Approach 2: Using Recursion
The above solution using loop is a iterative way of solving the problem. Let’s check how to reverse a number in java using recursion.
Algorithm
The approach will be similar to previous loop solution.But instead of looping, we will make recursive call to the function. The algorithm is as follows:
- Start with your original number, ‘num.’
- Initialize an empty variable called ‘rev’ to store the reversed number (rev = 0).
- Create a recursive function, ‘reverseRecursive,’ that takes ‘num‘ and ‘rev‘ as parameters.
- In the recursive function:
- Base Case:
- If num = 0, return ‘rev’ as the reversed number because there are no more digits to reverse.
- Recursive Step:
- Extract the last digit of ‘num’ using the modulo operator (num % 10).
- To build ‘rev,’ multiply the current ‘rev’ by 10 and then add the last digit obtained (10*rev + last_digit_of_num).
- Proceed to the next digit by dividing ‘num’ by 10 (disregard the remainder).
- Make a recursive call to ‘reverseRecursive’ with the updated ‘num’ and ‘rev.’
- Base Case:
- In the main program, call the ‘reverseRecursive’ function with the original number ‘num‘ and the initial ‘rev’ value of 0.
- The final reversed number will be the result.
Java Program To Reverse A Number Using Recursion
// Java Program To Reverse A Number Using Recursion
public class ReverseNumberRecursion {
public static int reverseRecursive(int num, int rev) {
// Base case: If num is 0, return the reversed number (rev)
if (num == 0) {
return rev;
}
// Extract the last digit of num
int lastDigit = num % 10;
// Build 'rev' by multiplying it by 10 and adding the last digit
rev = rev * 10 + lastDigit;
// Proceed to the next digit by dividing 'num' by 10
num /= 10;
// Make a recursive call with the updated 'num' and 'rev'
return reverseRecursive(num, rev);
}
public static void main(String[] args) {
int num = 12345; // Replace this with the number you want to reverse
int reversedNum = reverseRecursive(num, 0);
System.out.println("Reversed Number: " + reversedNum);
}
}
Output
Reversed Number: 54321
Code Explanation
Step | num | rev | Action |
---|---|---|---|
1 | 12345 | 0 | Initialize num and rev . |
2 | 12345 | 0 | Call reverseRecursive(12345, 0) . |
3 | 1234 | 5 | 1. Recursive call: extract last digit (12345 % 10 = 5) 2. Update rev to 0 * 10 + 5 = 53. Call reverseRecursive(1234, 5) . |
4 | 123 | 54 | 1. Recursive call: extract last digit (1234 % 10 = 4) 2. Update rev to 5 * 10 + 4 = 543. Call reverseRecursive(123, 54) . |
5 | 12 | 543 | 1. Recursive call: extract last digit (123 % 10 = 3) 2. Update rev to 54 * 10 + 3 = 5433. Call reverseRecursive(12, 543) . |
6 | 1 | 5432 | 1. Recursive call: extract last digit (12 % 10 = 2) 2. Update rev to 543 * 10 + 2 = 54323. Call reverseRecursive(1, 5432) . |
7 | 0 | 54321 | Recursive call: base case reached (num = 0), return rev (54321). |
8 | 12345 | 54321 | In the main program, display “Reversed Number: 54321”. |
The final reversed number is 54321, as shown in step 8.
Approach 3: Using String builder
Let’s check how to reverse a number in java using String builder
Algorithm
In this approach we will use String to reverse a number in java.
- Convert the num to a string.
- Create a
StringBuilder
object to store the reversed string. - Iterate through the characters of the string from right to left.
- Append each character to the
StringBuilder
in reverse order. - Convert the
StringBuilder
back to a integer to get the reversed number.
Java Program To Reverse A Number Using StringBuilder
// Java Program To Reverse A Number Using StringBuilder
public class ReverseNumberWithStringBuilder {
public static void main(String[] args) {
int num = 12345; // Replace this with the number you want to reverse
// Step 1: Convert the number to a string
String numString = Integer.toString(num);
// Step 2: Create a StringBuilder object to store the reversed string
StringBuilder reversedBuilder = new StringBuilder();
// Step 3 and Step 4: Iterate through the characters from right to left and append to StringBuilder
for (int i = numString.length() - 1; i >= 0; i--) {
reversedBuilder.append(numString.charAt(i));
}
// Step 5: Convert the StringBuilder back to an integer to get the reversed number
int reversedNum = Integer.parseInt(reversedBuilder.toString());
System.out.println("Reversed Number: " + reversedNum);
}
}
Output
Reversed Number: 54321
Code Explanation
Step | numString | reversedBuilder | Action |
---|---|---|---|
1 | “12345” | Empty | Initialize num and reversedBuilder . |
2 | “12345” | Empty | Convert num to a string (numString ). |
3 | “12345” | Empty | Create an empty StringBuilder . |
4 | “12345” | “5” | Append ‘5’ to reversedBuilder . |
5 | “12345” | “54” | Append ‘4’ to reversedBuilder . |
6 | “12345” | “543” | Append ‘3’ to reversedBuilder . |
7 | “12345” | “5432” | Append ‘2’ to reversedBuilder . |
8 | “12345” | “54321” | Append ‘1’ to reversedBuilder . |
9 | “12345” | 54321 | Convert reversedBuilder to a string. |
10 | “12345” | 54321 | Convert the reversed string to an integer. |
11 | “12345” | 54321 | Display the reversed number (54321). |
The final reversed number is 54321, as shown in step 11.
Space and Time Complexity
Method | Time Complexity | Space Complexity |
---|---|---|
Using a Loop | O(n) | O(1) |
Using Recursion | O(n) | O(n) |
Using StringBuilder | O(n) (amortized) | O(n) |
Note: In the context of these complexities, n
represents the number of digits in num
, which is equivalent to log10(num)
.
Key Takeaways
- Basic approach to reverse a number on extracting digits systematically from the number and reconstructing the reversed number from right to left.
- Recursive approach also follows similar digit extraction logic, but makes a recursive call repeatedly instead of a loop. Base case is reached when number becomes 0.
- Converting the number to a String allows leveraging StringBuilder to simply append characters in reverse order. StringBuilder can then be converted back to number.
Similar Posts
Add Days To The Current Date in Java
Calculate Area of Hexagon in Java
Program to Calculate EMI in Java
Calculate Area of a Circle in Java
Checkout more Java Tutorials here.
I hope You liked the post ?. For more such posts, ? subscribe to our newsletter. Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.
FAQ
How do I reverse a negative number in Java?
Reversing a negative number in Java follows the same principles as reversing a positive number. You can use the same algorithms, such as using a loop, recursion, or arrays. The key is to reverse the absolute value of the number and then restore the negative sign if necessary.
Can I reverse a floating-point number in Java?
Reversing a floating-point number (e.g., a decimal number) in Java typically involves reversing its digits while maintaining the decimal point’s position. You can convert the floating-point number to a string, reverse the string, and then parse it back to a floating-point number.
How can I check if a reversed number is a palindrome in Java?
To check if a reversed number is a palindrome in Java, follow these steps:
- Reverse the given number using one of the methods mentioned (loop, recursion, or arrays).
- Convert both the original and reversed numbers to strings.
- Compare the original and reversed strings. If they are the same, the number is a palindrome; otherwise, it’s not.