How To ReverseNumber in Java Program

How To ReverseNumber in Java Program

import java.util.Scanner;

public class ReverseNumber {
    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();
    }

    public static int reverseNumber(int number) {
        int reversedNumber = 0;
        while (number != 0) {
            int remainder = number % 10;
            reversedNumber = reversedNumber * 10 + remainder;
            number = number / 10;
        }
        return reversedNumber;
    }
}

Explanation:

1. Main Method:
– It prompts the user to enter a number.
– Reads the number using Scanner.
– Calls reverseNumber method and stores the reversed number.
– Finally, prints the reversed number.

2. reverseNumber Method:
– This function accepts an integer number as its parameter.
– Initializes reversedNumber to 0.
– Utilizes a while loop to invert the order of the number’s digits:
– Calculates the remainder (number % 10), which gives the last digit of number.
– Multiplies reversedNumber by 10 and adds the remainder (reversedNumber * 10 + remainder). This shifts the existing digits of reversedNumber to the left and adds the new digit at the end.
– Divides number by 10 to remove the last digit.
– Continues this process until number becomes 0.
– Returns reversedNumber.

This program effectively reverses any positive integer entered by the user.

Leave a Reply

Your email address will not be published. Required fields are marked *