In Java, we will learn how to write a program to reverse the digits of a given number in the Java programming language.
So let us know what we want to accomplish in this program before we proceed with writing the program.
Suppose someone enters a number like 456789 into the program. After performing the reverse operation, our Java program will return the output 987654.
We follow a logic here: first we take the last digit of the number entered and store it in a variable. Now we divide it by 10 so that we can find the middle number if it exists as the last number and append it to the previously stored number.
With this approach we can find the inverse number.
Reverse a number in Java
import java.util.*;
class Main {
public static void main(String ...a){
int reverse=0;
Scanner sc = new Scanner(System.in);
System.out.println("Please give a number: ");
int i = sc.nextInt();
while(i!=0){
reverse = reverse*10 + i%10;
i=i/10;
}
System.out.println("Number after reverse : "+reverse);
}
}
Output:
Please give a number:
56789
Number after reverse : 98765