public class ReverseNumber {
public static void main(String[] args) {
int num = 12345;
int reversed = 0;
for (; num != 0; num /= 10) {
int digit = num % 10;
reversed = reversed * 10 + digit;
}
System.out.println("Reversed number is " + reversed);
}
}
Reversed number is 54321
num
and initialize it with the value 12345. We then declare another integer variable reversed
and initialize it with 0. We then use a for loop to reverse the number. %
, and add it to the reversed number multiplied by 10. We then divide the original number by 10 to remove the last digit. We repeat this process until the original number becomes 0. Finally, we print the reversed number.public class ReverseNumber {
public static void main(String[] args) {
int num = 12345;
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed number is " + reversed);
}
}
Reversed number is 54321
public class ReverseNumber {
public static void main(String[] args) {
int num = 12345;
int reversed = reverse(num);
System.out.println("Reversed number is " + reversed);
}
public static int reverse(int num) {
if (num < 10) {
return num;
} else {
int lastDigit = num % 10;
int remainingDigits = num / 10;
int reversed = reverse(remainingDigits);
return lastDigit * (int)Math.pow(10, (int)Math.log10(remainingDigits) + 1) + reversed;
}
}
}
Reversed number is 54321
In this program, we first declare an integer variable num
and initialize it with the value 12345
. We then call the reverse
method, passing in num
, and store the returned value in the reversed variable. Finally, we print the reversed number.
The reverse
method is defined as a static method that takes an integer parameter num
and returns an integer. The method uses recursion to reverse the number. If the number is less than 10, it simply returns the number, since a single-digit number is already reversed. Otherwise, it extracts the last digit of the number using the modulus operator %
, and the remaining digits using integer division /
.
It then recursively calls itself with the remaining digits and stores the returned value in the reversed
variable. Finally, it computes the final reversed number by multiplying the last digit with 10 raised to the power of the number of digits in the remaining digits plus 1, and adding it to the reversed number.