Algorithm
- Input: Accept the input number from the user.
- Initialization: Set a variable to store the reversed number, initially to 0.
- Processing:
- Use a loop to extract digits from the input number one by one.
- Multiply the reversed number by 10 and add the extracted digit to it.
- Divide the input number by 10 to move to the next digit.
- Repeat the process until the input number becomes 0.
- Output: Display the reversed number.
Code Examples
#1 Code Example- Reverse a Number using a while loop in Java
Code -
Java Programming
class Main {
public static void main(String[] args) {
int num = 1234, reversed = 0;
System.out.println("Original Number: " + num);
// run loop until num becomes 0
while(num != 0) {
// get last digit from num
int digit = num % 10;
reversed = reversed * 10 + digit;
// remove the last digit from num
num /= 10;
}
System.out.println("Reversed Number: " + reversed);
}
}
Copy The Code &
Try With Live Editor
Output
Reversed Number: 4321
#2 Code Example- Reverse a number using a for loop in Java
Code -
Java Programming
class Main {
public static void main(String[] args) {
int num = 1234567, reversed = 0;
for(;num != 0; num /= 10) {
int digit = num % 10;
reversed = reversed * 10 + digit;
}
System.out.println("Reversed Number: " + reversed);
}
}
Copy The Code &
Try With Live Editor
Output
Reversed Number: 7654321
Demonstration
Java Programing Example to Reverse a Number-DevsEnv