Program to Find the Reverse of a Number
Definition & Explanation
The goal is to take an integer input, break down the number into its digits, and rearrange them in reverse order. Using loops and recursion, we will develop a program to determine the reverse of a given number in the Java language.
Example:
Input: 12345
Output: 54321
What need to be done?
Given an integer input, the aim is to find the reverse of the number in Java language.
Typically, this involves breaking down the number into its individual digits and subsequently rearranging them in reverse order.
C
Method 1 :
#include <stdio.h>
int main() {
// Given input number
int n = 12345;
// Initialize variables to store the reverse and remainder
int reverse = 0;
int remainder;
// Loop until the entire number is processed
while (n > 0) {
// Extract the last digit using the modulo operator
remainder = n % 10;
// Rearrange digits in reverse order
reverse = reverse * 10 + remainder;
// Reduce the number by one digit using division
n = n / 10;
}
// Output the final reversed number
printf("Reverse of the number: %d\n", reverse);
return 0;
}
Output :
Reverse of the number: 54321
C++
Method 1 :
#include <iostream>
int main() {
// Given input number
int n = 12345;
// Initialize variables to store the reverse and remainder
int reverse = 0;
int remainder;
// Loop until the entire number is processed
while (n > 0) {
// Extract the last digit using the modulo operator
remainder = n % 10;
// Rearrange digits in reverse order
reverse = reverse * 10 + remainder;
// Reduce the number by one digit using division
n = n / 10;
}
// Output the final reversed number
std::cout << "Reverse of the number: " << reverse << std::endl;
return 0;
}
Output :
Reverse of the number: 54321
JAVA
Method 1 :
public class Main {
public static void main(String[] args) {
// Given input number
int n = 12345;
// Initialize variables to store the reverse and remainder
int reverse = 0;
int remainder;
// Loop until the entire number is processed
while (n > 0) {
// Extract the last digit using the modulo operator
remainder = n % 10;
// Rearrange digits in reverse order
reverse = reverse * 10 + remainder;
// Reduce the number by one digit using division
n = n / 10;
}
// Output the final reversed number
System.out.println("Reverse of the number: " + reverse);
}
}
Output :
Reverse of the number: 54321
Python
Method 1 :
# Given input number
n = 12345
# Initialize variables to store the reverse and remainder
reverse = 0
remainder = 0
# Loop until the entire number is processed
while n > 0:
# Extract the last digit using the modulo operator
remainder = n % 10
# Rearrange digits in reverse order
reverse = reverse * 10 + remainder
# Reduce the number by one digit using division
n = n // 10
# Output the final reversed number
print("Reverse of the number:", reverse)
Output :
Reverse of the number: 54321