Summary: In this programming example, we will learn to reverse a number in Java.
Example:
Input: 123 Output: 321 Input: 5821 Output: 1285
There are multiple ways to reverse a number in Java. Let’s discuss each method one by one.
Method 1: Using While Loop
- Input a number (
num
). - Loop while
num!=0
:- Extract the last digit from
num
usingnum%10
and concatenate it to the reverse (rev
). - Remove the last digit from
num
usingnum/10
.
- Extract the last digit from
- Output the reverse.
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int num, rev =0, digit;
//Input a number
System.out.print("Enter a number: ");
num = in.nextInt();
//loop until num!=0
while(num!=0){
digit = num%10; //extract last digit
rev = 10*rev + num%10; //append the digit to the reverse
num = num/10; //remove the last digit
}
//output the reverse
System.out.println("Reversed Number: "+rev);
}
}
Output:
Enter a number: 123
Reversed Number: 321
Method 2: Without Using Another Variable
Unlike the above method, instead of appending the digits to the reverse vairiable, we can output them directly.
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
//Input a number
System.out.print("Enter a number: ");
int num = in.nextInt();
System.out.print("Reversed Number: ");
//loop until num!=0
while(num!=0){
System.out.print(num%10); //extract last digit and output
num = num/10; //remove the last digit from num
}
}
}
Output:
Enter a number: 1009
Reversed Number: 9001
The concept of reversing a number in java is useful in checking palindrome numbers.
Plzzz give all the questions answer and programs of icse 10