In this article, we will understand how to print an integer in Java. The reverse of a number is computed using a loop and arithmetic operator % and /.
Below is a demonstration of the same −
Input
Suppose our input is −
The number : 123456
Output
The desired output would be −
The result is 654321
Algorithm
Step 1 - START Step 2 - Declare three integer values namely my_input, reverse_input and remainder. Step 3 - Read the required values from the user/ define the values Step 4 – Run a while loop Step 5- Use modulus of 10 and get remainder for ‘my_remainder’ . Step 6- Multiply ‘reverse_input’ with 10, and add to ‘my_remainder’, and make that the current ‘reverse_input’. Step 7- Divide ‘my_input’ by 10, and make that the current ‘my_input. Step 8- Display the result Step 9- Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool .
import java.util.Scanner; public class ReverseNumber{ public static void main(String[] args){ int my_input , reverse_input, my_remainder; reverse_input = 0; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.print("Enter the number : "); my_input = my_scanner.nextInt(); while(my_input != 0){ my_remainder = my_input % 10; reverse_input = reverse_input * 10 + my_remainder; my_input = my_input/10; } System.out.println("The reverse value of the given input is: " + reverse_input); } }
Output
Required packages have been imported A reader object has been defined Enter the number : 123456 The reverse value of the given input is: 654321
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class ReverseNumber{ public static void main(String[] args){ int my_input , reverse_input; my_input = 123456; reverse_input = 0; System.out.println("The number is defined as " +my_input); while(my_input != 0){ int remainder = my_input % 10; reverse_input = reverse_input * 10 + remainder; my_input = my_input/10; } System.out.println("The reverse value of the given input is: " + reverse_input); } }
Output
The number is defined as 123456 The reverse value of the given input is: 654321