Program To Reverse A Given Number In Java
Reversing a number is a common programming challenge that involves manipulating its digits. This process can be useful in various scenarios, such as checking for palindromes or performing specific mathematical operations. In this article, you will learn how to reverse a given number in Java using several approaches.
Problem Statement
The problem is to take an integer as input and return a new integer with its digits reversed. For example, if the input is 123, the output should be 321. If the input is 500, the output should be 5.
Example
Input: 12345
Output: 54321
Background & Knowledge Prerequisites
To understand the solutions presented, you should have a basic understanding of:
- Java primitive data types:
int,long - Arithmetic operators:
%(modulo),/(division),*(multiplication),+(addition) - Control flow statements:
whileloops - String manipulation:
StringBuilder(for one approach)
Use Cases or Case Studies
- Palindrome Check: Reversing a number is a fundamental step in determining if a number is a palindrome (reads the same forwards and backward, e.g., 121).
- Data Transformation: In some algorithms, reversing the order of digits might be required for specific data transformations.
- Educational Exercises: It's a classic problem used to teach basic arithmetic operations and loop structures in programming.
- Number Puzzles: Certain mathematical puzzles or games might involve reversing numbers.
- Display Formatting: Though less common, sometimes numbers need to be displayed in reverse order for specific UI requirements.
Solution Approaches
We will explore three common methods to reverse a number in Java:
- Using a
whileloop and arithmetic operations. - Using
StringBuilderfor string manipulation. - Using recursion.
Approach 1: Using a while loop and arithmetic operations
This is the most common and often preferred method as it avoids string conversions, making it efficient for numerical operations.
- One-line summary: Extracts digits one by one using the modulo operator and reconstructs the reversed number.
// Reverse Number using While Loop
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Get input from the user
System.out.print("Enter a number to reverse: ");
int originalNumber = scanner.nextInt();
int number = originalNumber;
int reversedNumber = 0;
// Step 2: Use a while loop to extract and reverse digits
while (number != 0) {
int digit = number % 10; // Extract the last digit
reversedNumber = reversedNumber * 10 + digit; // Append the digit to reversedNumber
number /= 10; // Remove the last digit from the number
}
// Step 3: Print the reversed number
System.out.println("Original number: " + originalNumber);
System.out.println("Reversed number: " + reversedNumber);
scanner.close();
}
}
- Sample output:
Enter a number to reverse: 12345
Original number: 12345
Reversed number: 54321
- Stepwise explanation:
- Initialize
reversedNumberto 0. This variable will store the result. - Start a
whileloop that continues as long asnumberis not 0. - Inside the loop,
digit = number % 10extracts the last digit ofnumber. For example, ifnumberis 123,digitbecomes 3. reversedNumber = reversedNumber * 10 + digitbuilds the reversed number. Each extracted digit is appended toreversedNumberby multiplyingreversedNumberby 10 (shifting existing digits to the left) and then adding the newdigit.number /= 10removes the last digit fromnumber. For example, ifnumberwas 123, it becomes 12.- The loop repeats until
numberbecomes 0, at which point all digits have been processed.
Approach 2: Using StringBuilder
This method converts the number to a string, reverses the string, and then converts it back to a number.
- One-line summary: Converts the number to a string, uses
StringBuilder'sreverse()method, and then parses it back to an integer.
// Reverse Number using StringBuilder
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Get input from the user
System.out.print("Enter a number to reverse: ");
int originalNumber = scanner.nextInt();
// Step 2: Convert the number to a String
String numberAsString = String.valueOf(originalNumber);
// Step 3: Use StringBuilder to reverse the string
StringBuilder stringBuilder = new StringBuilder(numberAsString);
stringBuilder.reverse();
// Step 4: Convert the reversed string back to an integer
int reversedNumber = Integer.parseInt(stringBuilder.toString());
// Step 5: Print the reversed number
System.out.println("Original number: " + originalNumber);
System.out.println("Reversed number: " + reversedNumber);
scanner.close();
}
}
- Sample output:
Enter a number to reverse: 9876
Original number: 9876
Reversed number: 6789
- Stepwise explanation:
- The
originalNumberis converted into aStringusingString.valueOf(). - A
StringBuilderobject is created with this string. - The
reverse()method ofStringBuilderis called, which reverses the sequence of characters in place. - The reversed
StringBuilderis converted back to aStringusingtoString(). - Finally,
Integer.parseInt()converts the reversed string back into anint.
Approach 3: Using Recursion
Recursion offers a more elegant, albeit sometimes less efficient,