Java Practice Program: reverses given number

Write a Java program to reverse the digits of a given number

This program reverses the digits of a given number (userNo) and outputs the reversed number. Here’s an explanation:

What Does the Program Do?
The program takes an integer (e.g., 123), reverses its digits (to 321), and prints the result.

For example:

  • Input: 123
  • Reverse: 321
  • Output: 321
class Main {
    public static void main(String[] args) {
        int rev = 0;
        int userNo = 123;  // Number to reverse

        // Loop to reverse the digits of the number
        while (userNo != 0) {
            int digit = userNo % 10;  // Get the last digit
            rev = rev * 10 + digit;   // Shift rev left and add the digit
            userNo /= 10;             // Remove the last digit from userNo
        }

        // Print the reversed number
        System.out.print(rev);
    }
}

Output

For userNo = 123, the output is:

321

Input Initialization:

  • userNo = 123: The number to reverse.
  • rev = 0: A variable to store the reversed number.

Digit Extraction and Reversal:

  • Loop Condition: Runs until userNo becomes 0.
  • Logic inside the loop:
    • userNo % 10: Extracts the last digit of userNo.
      Example: For 123, 123 % 10 = 3 (last digit).
    • rev = rev * 10 + digit: Shifts rev one digit to the left by multiplying it by 10, then adds the extracted digit to it.
      Example: If rev = 0 and digit = 3, then rev = 0 * 10 + 3 = 3.
    • userNo /= 10: Removes the last digit from userNo by performing integer division by 10.
      Example: After removing the last digit, userNo = 123 / 10 = 12.

Iteration Breakdown for userNo = 123:

  • Iteration 1:
    • Extract last digit: digit = 3
    • Update rev: rev = 0 * 10 + 3 = 3
    • Update userNo: userNo = 123 / 10 = 12
  • Iteration 2:
    • Extract last digit: digit = 2
    • Update rev: rev = 3 * 10 + 2 = 32
    • Update userNo: userNo = 12 / 10 = 1
  • Iteration 3:
    • Extract last digit: digit = 1
    • Update rev: rev = 32 * 10 + 1 = 321
    • Update userNo: userNo = 1 / 10 = 0
  • Loop ends when userNo becomes 0.

Output the Result:

  • After the loop, rev contains the reversed number.
  • The program prints rev using System.out.print().

Leave a Reply