Java Program to Reverse a Number

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 SNIPPET
class 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

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024