Reverse an Integer in Java


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;
}

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements