Java

A reverse number is a numerical value whose digits are arranged in the opposite order from the original number. For example, the reverse of 12345 is 54321. 

Understanding the Code:

1.   The code starts by initializing a variable number with a sample value (12345 in this case).

2.   Inside the main method, the code initializes numberWithoutLastDigit to store the original number without its last digit, and reversedNumber to store the reversed number.

3.   The main logic is implemented within a while loop that continues until the original number becomes zero.

4.   Inside the loop, the last digit of the original number is extracted using the modulus operator (%). This digit is then added to the reversedNumber after multiplying it by 10 to shift the existing digits to the left.

5.   The original number is updated by removing its last digit through integer division (/).

6.   The code prints each digit extracted and the current value of the reversed number in each iteration for visualization and debugging purposes.

7.   Once all digits are processed, the loop terminates, and the reversed number is printed.

// 12345 -- 54321


public class ReverseNumber {
    public static void main(String[] args) {
       
        int number=12345;


       
        int numberWithoutLastDigit=number/10;


        int reversedNumber=0;


        while (number!=0) {
            int digit=number%10;
            System.out.println("Digit:"+digit);
            reversedNumber=reversedNumber*10+digit;
            System.out.println("R:"+reversedNumber);
            number=number/10;
            System.out.println("Number:"+number);
            System.out.println("--------------------------");
           
        }


    }
}

Conclusion : The Reverse Number algorithm in Java efficiently reverses the digits of a given number through basic arithmetic operations and looping constructs. The repeated process of removing digits from the original number and creating the reversed number up until all digits are processed is demonstrated by this code.

Related Posts

Table Of Contents

;