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

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


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.

Comments

Popular Posts from this Blog

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

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

InterviewBit - Colorful Number Solution - The Coding Shala