Java Program to Reverse a Number - The Coding Shala

Home >> Java Programs >> Reverse a Number

 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


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(;
		// 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);


Enter a Number: 
Reversed Number is: 415

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala