Printing a number in reverse order in Java involves extracting the digits of the number one by one and printing them in reverse. Here's the Java code to print a number in reverse order:
public class ReverseNumber {
public static void main(String[] args) {
int number = 12345;
System.out.println("Original number: " + number);
System.out.print("Number in reverse: ");
printReverseNumber(number);
}
public static void printReverseNumber(int num) {
while (num > 0) {
int digit = num % 10; // Extract the last digit
System.out.print(digit);
num /= 10; // Remove the last digit
}
}
}
- In this example, we take an integer number (e.g., 12345) as input.
- The printReverseNumber method is used to print the digits of the number in reverse order.
- Inside the printReverseNumber method, we use a while loop that runs as long as num is greater than 0.
- In each iteration of the loop, we extract the last digit of num using the modulus operator (num % 10) and print it.
- We then remove the last digit from num by dividing it by 10 (num /= 10).
- The loop continues until all digits of the number are printed.
No comments:
Post a Comment