Java Program to Reverse a Number - The Coding Shala
Home >> Java Programs >> Reverse a Number
Other Posts You May Like
In this post, we will learn how to Reverse a Number in Java.
Java Program to Reverse a Number
Take a number as input and Write a Java Program to Reverse the given number.
Example 1:
Input: 213
Output: 312
Approach
Step 1: Take the last digit using the number % 10. the Modulo (%) operator returns the remainder.
Step 2: Append this last digit to reversed number. Reverse = Reverse * 10 + lastdigit
Step 3. Remove the last digit from the number using the number / 10.
Java Program:
// Java program to Reverse a Number import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // take input System.out.println("Enter a Number: "); int num = sc.nextInt(); int reverseNum = 0; while(num > 0) { // take last digit; int digit = num % 10; // add it in reverse reverseNum = reverseNum * 10 + digit; // remove last digit from number num = num / 10; } System.out.println("Reversed Number is: " + reverseNum); sc.close(); } }
Output:
Enter a Number: 514 Reversed Number is: 415
- Java Program to Check Armstrong Number
- Java Program to Check Prime Number
- Java Program to Count Number of Vowels in a String
- Java Program to Reverse a String
- Java Program to Reverse a String using Recursion
Comments
Post a Comment