Reverse an Integer in Java

Java 8Object Oriented ProgrammingProgramming

To reverse an integer in Java, try the following code −

Example

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      int i = 239, rev = 0;
      System.out.println("Original: " + i);
      while(i != 0) {
         int digit = i % 10;
         rev = rev * 10 + digit;
         i /= 10;
      }
      System.out.println("Reversed: " + rev);
   }
}

Output

Original: 239
Reversed: 932

In the above program, we have the following int value, which we will reverse.

int i = 239;

Now, loop through until the value is 0. Find the remainder and perform the following operations to get the reverse of the given integer 239.

while(i != 0) {
   int digit = i % 10;
   rev = rev * 10 + digit;
   i /= 10;
}
raja
Published on 13-Nov-2018 09:18:32
Advertisements