Home page

Sunday, August 6, 2023

Reverse number in JAVA

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

        }

    }

}

Output:
Original number: 12345
Number in reverse: 54321

Explanation:
  1. In this example, we take an integer number (e.g., 12345) as input.
  2. The printReverseNumber method is used to print the digits of the number in reverse order.
  3. Inside the printReverseNumber method, we use a while loop that runs as long as num is greater than 0.
  4. In each iteration of the loop, we extract the last digit of num using the modulus operator (num % 10) and print it.
  5. We then remove the last digit from num by dividing it by 10 (num /= 10).
  6. The loop continues until all digits of the number are printed.
The code prints the original number and then uses the printReverseNumber method to print the number in reverse order by extracting and printing the digits from right to left.

This approach works for positive integers. If you need to handle negative numbers or non-integer values, you can adapt the code accordingly.

No comments:

Post a Comment