Java Program to Reverse a Number
Program
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
int number = 0, reverse = 0, remainder = 0;
System.out.print("Enter a number:\t");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
while (number != 0) {
remainder = number % 10;
reverse = reverse * 10 + remainder;
number = number / 10;
}
System.out.println("Reversed number is:\t" + reverse);
}
}
Let us understand the program by breaking into simple parts:
number
, reverse
, and remainder
are declared as int and initialized to 0. These variables will hold the original number, its reverse, and the remainder of the original number respectively.
The user is prompted to Enter a number using System.out.print("Enter a number:\t");
and the user input is read using Scanner
object using Scanner sc = new Scanner(System.in);
and inputted value is stored in number variable.
The main logic to reverse the number starts from while(number != 0)
.
- Inside the loop, the remainder of the original number when divided by 10 is calculated using the expression
remainder = number % 10;
. This gives the last digit of the original number. - The last digit is then appended to the reverse variable after shifting the existing digits of reverse one place to the left, and adding the remainder:
reverse = reverse * 10 + remainder;
. - The last digit is removed from the original number by integer division:
number = number / 10;
.
Once the while loop finishes i.e., when the original number becomes 0, the reversed number stored in the reverse
variable is printed to the console using System.out.println("Reversed number is:\t" + reverse);
.
Consider an example to illustrate step by step process of reversing a number:
Let's say the user enters the number 123
.
- First iteration of the loop:
- remainder = 123 % 10 which gives 3.
- reverse = 0 * 10 + 3 which gives 3.
- number = 123 / 10 which gives 12.
- Second iteration of the loop:
- remainder = 12 % 10 which gives 2.
- reverse = 3 * 10 + 2 which gives 32.
- number = 12 / 10 which gives 1.
- Third iteration of the loop:
- remainder = 1 % 10 which gives 1.
- reverse = 32 * 10 + 1 which gives 321.
- number = 1 / 10 which gives 0.
Since number becomes 0, the loop terminates. The reversed number, which is 321
, is printed to the console.
Output
Enter a number: 478294
Reversed number is: 492874