We can write a java program to reverse a number in a lot of ways. Some of those ways are using for loop, using while loop and recursion.
Java program to reverse a number using while loop
public class DeveloperHelps {
public static void main(String[] args) {
int num = 1612, reverse = 0;
while(num != 0) {
int i = num % 10;
reverse = reverse * 10 + i;
num /= 10;
}
System.out.println("The reversed number is: " + reverse);
}
}
The output of the following program is:
2161
In the above program, first the remainder of the number is divided by 10 and then stored in the βiβ variable. Now, the βiβ variable contains last digit of the number that we have entered which is 2.
Then, we add i to reverse and multiply it by 10. As a result, it adds new place in the reversed number. Hence, the onesβ place is multiplied by 10 gives us the tenth place of the number. Similarly, the tenth places will give the hundreds place and so on. In this way, the iterations happen and the digit is reversed.
Reverse the number using for loop
public class DeveloperHelps {
public static void main(String[] args) {
int num = 1612, reverse = 0;
for(;num != 0; num /= 10) {
int i = num % 10;
reverse = reverse * 10 + i;
}
System.out.println("The reversed number is: " + reverse);
}
}
The output of the above program will be:
The reversed number is: 2161
In the program using or loop, we do not use any initialization expression. Here, the test expression remains the same as while loop which is num!=0. we increment the expression as num/=10. As a result, after each iteration the new expression keeps on removing the last digit of the number. So, the final output will contain the reversed number, as we finish the loop.
We can also perform the reverse of a number using recursion.
import static java.lang.StrictMath.pow;
import java.util.Scanner;
public class DeveloperHelps
{
public static void main(String[] args)
{
int f, count = 0, m;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number which you want to be reversed:");
f = s.nextInt();
m = f;
while(m > 0)
{
count++;
m = m / 10;
}
DeveloperHelps obj = new DeveloperHelps();
int a = obj.reverse(f, count);
System.out.println("Reverse:"+a);
}
int reverse(int x, int length) {
if(length == 1) {
return x;
}
else{
int b = x % 10;
x = x / 10;
return (int) ((b * pow(10, length - 1)) + reverse(x, --length));
}
}
}
The output of the above program will be:
Enter the number which you want to be reversed:
1612
2161