In this post you will learn basic java program that reverses the digits of a number and print the reversed number.
Problem:
Here is the example of the problem –
Example 1:
Input : 5678 Output :8765
Example 2:
Solutions:
- First, we find the remainder of the given number by using the modulo (%) operator.
- Multiply the variable reverse by 10 and add the remainder into it.
- Divide the number by 10.
There are three ways to reverse a number in java:
- Reverse a number using while loop.
- Reverse a number using for loop.
- Reverse a number using recursion.
Approach 1 : Reverse a number using loops
public class ReverseNumber { public static void main(String[] args) { int number = 12345, reverse = 0; while(number != 0) { int remainder = number % 10; reverse = reverse * 10 + remainder; number = number/10; } System.out.println("The reverse of the given number is: " + reverse); } }
Output:
The reverse of the given number is: 54321
Approach 2 : Reverse a number using recursion:
import java.util.Scanner; public class ReverseNumber { //method for reverse a number public static void reverseNumber(int number) { if (number < 10) { //prints the same number if the number is less than 10 System.out.println(number); return; } else { System.out.print(number % 10); reverseNumber(number/10); } } public static void main(String args[]) { System.out.print("Enter the number that you want to reverse: "); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); System.out.print("The reverse of the given number is: "); //method calling reverseNumber(num); } }
Output:
Enter the number that you want to reverse: 1413 The reverse of the given number is: 3141
More java programs:
Java Program to Print Multiplication Table of a Number
Java Program to Get Input from User
Java Program to Count Number of Digits in a Number