1.

Reverse an Integer in Java

Answer»

Reversing an integer involves reversing all of its DIGITS. An example of this is given as follows:

Integer = 123 Reverse of the integer = 321

A program that demonstrates reversing an integer in Java is given as follows:

public class Demo {   public static void main(String args[])   {      int num = 2413, rev = 0;      System.out.println("The number is " + num);      while(num != 0)      {          rev = rev * 10;          rev = rev + num % 10;          num = num / 10;      }      System.out.println("Reverse of the above number is " + rev);   } }

The OUTPUT of the above program is as follows:

The number is 2413 Reverse of the above number is 3142

In the above program, the number 2413 is REVERSED using a while loop and the result is stored in rev which is then DISPLAYED.



Discussion

No Comment Found