To reverse the digits of a number in Java, you can use a loop to iterate through the digits of the number in reverse order and build a new number by adding each digit to the right side of the result number.
Here's an example of how you can reverse the digits of a number in Java:
class Main { public static void main(String[] args) { int num = 12345; int reversed = reverseNumber(num); System.out.println(reversed); } public static int reverseNumber(int num) { int reversed = 0; while (num > 0) { reversed = reversed * 10 + num % 10; num /= 10; } return reversed; } }
In this example, the reverseNumber
method takes an integer as an argument and returns an integer that is the reverse of the input number. The loop starts with the least significant digit of the number and iterates through each digit, adding it to the right side of the reversed
number and multiplying the reversed
number by 10
to shift the digits to the left. The num
variable is divided by 10
at the end of each iteration to move to the next digit.
This method will work for any integer, including negative numbers. If the input number is negative, the resulting reversed number will also be negative. If you want to reverse the digits of a positive number and ignore the sign, you can use the Math.abs
function to get the absolute value of the number before reversing it.