In this program, we are going to see how we can reverse any user given number. Reversing any word, phrase or number is pretty simple if we treat it as a string data. We can simply iterate through each character in reverse order and then append it to one temporary variable. But here we are only dealing with numbers and for numbers, there is a better approach.
Logic
First of all, we have to declare one temporary variable reverse with value 0, we will use this variable to store the reverse of the number.
After taking input from the user, we have to assign the input to one temporary variable temp, Now to reverse a number we have to extract each digit of that number one by one. To extract digits we can use % (modulo) operator. If we perform modulo operation with 10 on any number it will return the last most digit.
Now after extracting the digit, we have to append it to our temporary variable reverse, but we cannot directly append the digit on it. To append the digit, first, we need to multiply 10 on existing reversed value and then perform addition with the extracted digit.
At the end remove the last most digit and repeat the same again until the value of temp becomes 0 or less than 0.
Once the loop is finished simply print the variable reverse.
Program
import java.util.Scanner; public class ReverseNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Take numbers from user System.out.print("Enter any number : "); int num = scanner.nextInt(); int temp = num; int reverse = 0; while(temp != 0) { reverse = (reverse * 10) + (temp % 10); temp /= 10; } System.out.println("\nReverse of " + num + " : " + reverse); } }
Output
Enter any number : 123456
Reverse of 123456 : 654321