Seo Forum

Coding & Programming => Programming Forum => Topic started by: sonakshibhathi on 08-01-2017, 03:53:42

Title: How to reverse an integer in Java?
Post by: sonakshibhathi on 08-01-2017, 03:53:42
Hi friends,
I would like to know,
How to reverse an integer in Java?
Title: Re: How to reverse an integer in Java?
Post by: greatshivam on 02-24-2020, 05:49:14
Example-
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;
}