Coding & Programming > Programming Forum

How to reverse an integer in Java?

(1/1)

sonakshibhathi:
Hi friends,
I would like to know,
How to reverse an integer in Java?

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

brookeroberts7:
class ReverseNumber. { public static void main(String args[]) { int n, reverse = 0;
System. out. println("Enter an integer to reverse"); Scanner in = new Scanner(System. in); n = in. nextInt();
while(n != 0) { reverse = reverse * 10; reverse = reverse + n%10; n = n/10; }

Lishmalinyjames:
class ReverseNumber. { public static void main(String args[]) { int n, reverse = 0;
System. out. println("Enter an integer to reverse"); Scanner in = new Scanner(System. in); n = in. nextInt();
while(n != 0) { reverse = reverse * 10; reverse = reverse + n%10; n = n/10; }