Java program to reverse a number
Here's an example Java program that reverses a 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("Original number: " + 12345); System.out.println("Reversed number: " + reversed); } }Source:www.theitroad.com
This program first initializes a variable num
with the original number to be reversed, and a variable reversed
with an initial value of 0. The program then uses a while loop to repeatedly extract the rightmost digit of num
using the modulus operator %
, add it to the reversed number reversed
by multiplying it by 10 and adding the current digit, and divide num
by 10 to remove the rightmost digit. This process is repeated until num
becomes 0.
The program then prints the original and reversed numbers to the console.
The output of this program would be:
Original number: 12345 Reversed number: 54321