In this Java program, you’ll learn how to Reverse a Number using Java programming language.
How to reverse a number?
Example 1: using for loop
[Maxbutton id=”1″ url=”https://coderseditor.com/?id=824″ text=”RUN CODE SNIPPET” ]
class Main { public static void main(String[] args) { int num = 123456789, reversed = 0; for(;num != 0; num /= 10) { int digit = num % 10; reversed = reversed * 10 + digit; } System.out.println("Reversed Number: " + reversed); } }
OUTPUT
Reversed Number: 987654321
Example 2: using while loop
RUN CODE SNIPPETclass Main { public static void main(String[] args) { int num = 123456789, reversed = 0; while(num != 0) { int digit = num % 10; reversed = reversed * 10 + digit; num /= 10; } System.out.println("Reversed Number: " + reversed); } }
OUTPUT
Reversed Number: 987654321