reverse a integer in java

To reverse an integer in Java, you can follow these steps:

  1. Initialize the integer variable to be reversed. Let's call it "num".
  2. Create a variable called "reversed" and set it to 0. This variable will hold the reversed value of the integer.
  3. Iterate over each digit of the integer using a while loop. Inside the loop, perform the following steps: a. Get the last digit of "num" by using the modulus operator (%). Assign the result to a variable called "digit". b. Multiply "reversed" by 10 and add "digit" to it. This will shift the existing digits in "reversed" to the left and append the current digit at the end. c. Divide "num" by 10 to remove the last digit.
  4. Repeat steps 3a-3c until "num" becomes 0.
  5. After the loop ends, the variable "reversed" will hold the reversed value of the original integer.

Here is the code snippet that implements the above steps:

int num = 12345;
int reversed = 0;

while (num != 0) {
    int digit = num % 10;
    reversed = reversed * 10 + digit;
    num /= 10;
}

System.out.println("Reversed number: " + reversed);

This code will reverse the integer 12345 and print the result as 54321.