Reverse a Number in Java - A Quick and Easy Guide
Reverse a Number in Java
In this article, we will learn how to reverse a number in Java. Although the task is quite easy, there are certain subtleties to consider when implementing it.
To reverse a number in Java, we need to use a simple iteration and keep track of the digits present in the number. We can use a while loop to iterate through each digit of the number, one at a time. Then, we can use the modulus operator (%) to find the last digit and append it to a new string or variable. We can also use integer division (/) to remove the last digit from the number at every iteration.
The below Java program shows how to reverse a number.
public class ReverseNumber { public static void main(String[] args) { int number = 12345; int reversedNumber = 0; int temp = 0; while(number > 0){ // Use modulus operator to strip off the last digit temp = number%10; // Create the reversed number reversedNumber = reversedNumber * 10 + temp; number = number/10; } System.out.println("Reversed Number: " + reversedNumber); } }
The output of the above program would be Reversed Number: 54321.
We hope that this article helped you understand how to reverse a number in Java. To learn more about Java programming and problem solving, check out our other tutorials!