Reverse A Number In Java Using While Loop
Reversing a number is a common programming task that involves reordering its digits from last to first. This operation can be useful in various scenarios, such as checking for palindromes or manipulating numerical data. In this article, you will learn how to reverse a number in Java using a while loop.
Problem Statement
Given an integer, the goal is to produce a new integer where the order of the digits is reversed. For example, if the input is 123, the output should be 321. This problem requires digit-by-digit processing of the number.
Example
If the input number is 54321, the reversed number will be 12345.
Background & Knowledge Prerequisites
To understand this article, you should have a basic understanding of:
- Java variables and data types: Specifically, integers (
int). - Arithmetic operators: Modulo (
%) for getting the last digit and division (/) for removing the last digit. -
whileloops: For repetitive execution based on a condition.
Use Cases or Case Studies
Reversing a number has several practical applications:
- Palindrome Check: Determining if a number reads the same forwards and backward (e.g.,
121is a palindrome). - Number Manipulation: Creating new numbers based on the reversed order of digits.
- Cryptography (simple forms): As a basic transformation step in some algorithms.
- Educational Exercises: A fundamental problem for learning loop control and arithmetic operations.
- Display Formatting: Sometimes numbers need to be displayed in a reversed order for specific UI requirements.
Solution Approaches
We will focus on one primary approach using a while loop, as it's the most common and intuitive method for this problem.
Approach 1: Using a while loop and arithmetic operations
This approach iteratively extracts the last digit of the number, appends it to a reversedNumber, and then removes it from the original number until the original number becomes zero.
- One-line summary: Extract digits using the modulo operator and build the reversed number using multiplication and addition within a
whileloop.
// Reverse a 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) {
// Step 1: Initialize a Scanner to read input from the user
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt the user to enter a number
System.out.print("Enter a number to reverse: ");
int originalNumber = scanner.nextInt();
// Step 3: Initialize a variable to store the reversed number
int reversedNumber = 0;
int tempNumber = originalNumber; // Use a temporary variable to avoid modifying originalNumber
// Step 4: Use a while loop to extract digits and build the reversed number
while (tempNumber != 0) {
int digit = tempNumber % 10; // Get the last digit
reversedNumber = reversedNumber * 10 + digit; // Append the digit to reversedNumber
tempNumber /= 10; // Remove the last digit from tempNumber
}
// Step 5: Print the original and reversed numbers
System.out.println("Original Number: " + originalNumber);
System.out.println("Reversed Number: " + reversedNumber);
// Step 6: Close the scanner
scanner.close();
}
}
- Sample output:
Enter a number to reverse: 12345
Original Number: 12345
Reversed Number: 54321
- Stepwise explanation for clarity:
- Initialization:
-
originalNumber: Stores the number provided by the user. -
reversedNumber: Initialized to0. This variable will accumulate the reversed digits. -
tempNumber: A copy oforiginalNumberis made totempNumber. This is crucial because we need to modifytempNumberin the loop without losing the original value for printing.
whileloop condition:
- The loop continues as long as
tempNumberis not0. This ensures that all digits of the number are processed.
- Inside the loop:
-
int digit = tempNumber % 10;: The modulo operator (%) gives the remainder whentempNumberis divided by10. This effectively extracts the last digit (e.g.,123 % 10is3). -
reversedNumber = reversedNumber * 10 + digit;: -
reversedNumber * 10: Shifts the existingreversedNumberone decimal place to the left (e.g., ifreversedNumberis0, it becomes0; ifreversedNumberis3, it becomes30). -
+ digit: Adds the newly extracteddigitto the shiftedreversedNumber(e.g.,0 + 3becomes3;30 + 2becomes32). This effectively appends the digit. -
tempNumber /= 10;: The integer division operator (/) dividestempNumberby10and discards the remainder. This effectively removes the last digit fromtempNumber(e.g.,123 / 10becomes12).
- Loop Termination:
- When
tempNumbereventually becomes0, it means all digits have been processed, and the loop terminates.
- Output:
- The
originalNumberand the finalreversedNumberare printed.
Conclusion
Reversing a number using a while loop in Java is a fundamental programming exercise that demonstrates the effective use of arithmetic operators for digit manipulation. This method is efficient and straightforward for handling integer reversal.
Summary
- Problem: Reorder digits of an integer from last to first.
- Method: Use a
whileloop to repeatedly extract the last digit, build the reversed number, and remove the last digit from the original. - Key Operators:
-
% 10: Extracts the last digit. -
/= 10: Removes the last digit. -
* 10 + digit: Appends the extracted digit to thereversedNumber. - Variables: An
originalNumber, atempNumberfor iteration, and areversedNumberto store the result.