In this blog post, we will learn how to write a Java program to reverse a number step by step.
Reversing a number might seem like a trivial task, but when you’re just starting with programming, it can be a fun and challenging problem.
The Problem Statement
Given a number, say 12345, we want to reverse it, so the result will be 54321.
Program Explanation
Before writing the program, let’s break down the process into steps:
Initialize the reversed number: Start with a variable called reversed and set it to 0.
Loop until the number is not zero: The loop will serve to extract digits from the original number one by one.
Extract the last digit: Use the modulo operator % to get the last digit of the number.
Append the extracted digit to the reversed number: Multiply the reversed number by 10 (to shift its digits to the left) and then add the extracted digit.
Remove the last digit from the original number: Use the division operator / to remove the last digit.
Repeat: Continue the process until the original number is 0.
Java Program
As per above program explanation, let's write the Java program to reverse a number:
public class ReverseNumber {
public static int reverse(int number) {
int reversed = 0; // Step 1:Initialize the reversed number
while (number != 0) { // Step 2: Loop until the number is not zero
int digit = number % 10; // Step 3: Extract the last digit
reversed = reversed * 10 + digit; // Step 4: Append the digit to reversed
number = number / 10; // Step 5: Remove the last digit
}
return reversed;
}
public static void main(String[] args) {
int originalNumber = 12345;
int reversedNumber = reverse(originalNumber);
System.out.println("Original Number: " + originalNumber);
System.out.println("Reversed Number: " + reversedNumber);
}
}
Output:
Original Number: 12345
Reversed Number: 54321
Understanding Core Logic
int digit = number % 10: This line of code finds the remainder when our number is divided by 10, which effectively gives us the last digit of the number.
reversed = reversed * 10 + digit: Here, we shift the digits of reversed to the left by multiplying by 10, then add the extracted digit. This effectively appends the digit to the end.
number = number / 10: By dividing the number by 10, we remove its last digit.
Conclusion
In this post, we learned how to write a Java program to reverse a number step by step and we understood the core logic of the program.
Happy coding!
Comments
Post a Comment
Leave Comment