In the realm of programming, learning the fundamentals is crucial, and one of the fundamental skills is to manipulate numbers. One such interesting exercise is reversing a number. In this article, we’ll explore how to write a simple Java program that reverses a given number.
Table of Contents
Understanding the Problem
The task at hand involves taking an input number and reversing its digits. For example, if the input number is 12345, the reversed number would be 54321. To achieve this, we’ll employ simple mathematical operations in Java.
Approach and Implementation
Let’s dive into the implementation of the number reversal program in Java
Java Program to Reverse A Number
package com.gangforcode;
import java.util.Scanner;
public class NumberReversal {
// main method
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to reverse: ");
int number = scanner.nextInt();
int reversedNumber = reverseNumber(number);
System.out.println("Reversed number: " + reversedNumber);
scanner.close();
}
// Method to reverse the number
public static int reverseNumber(int num) {
int reversedNum = 0;
while(num != 0) {
int digit = num % 10; // Extract the last digit
reversedNum = reversedNum * 10 + digit; // Append the digit to reversedNum
num /= 10; // Move to the next digit
}
return reversedNum;
}
}
Output
Explanation of Reverse Number Program in Java
- The program begins by importing the
Scanner
class to take user input. - It prompts the user to input a number using
Scanner.nextInt()
. - The
reverseNumber
method takes an integer parameternum
and initializesreversedNum
to 0. - Using a while loop, the program iterates through each digit of the input number:
digit
stores the last digit of the number using the modulo operator%
.reversedNum
is updated by appending the digit and multiplying the current reversed number by 10 to shift its digits to the left.num
is divided by 10 to remove the last digit and proceed to the next digit.- Finally, the reversed number is returned and displayed to the user.
In conclusion, this article delved into a simple yet essential programming exercise: reversing a number in Java. By leveraging fundamental mathematical operations and a straightforward algorithm, we successfully reversed the digits of a given number. Understanding these basics lays a solid foundation for more complex programming challenges.
2 thoughts on “Reverse Number Program in Java”