How to Reverse a Number in Java using while loop

If you have a foundation in computer science, broadening your technical knowledge is the finest thing you can do. However, your programming abilities are the most important, and you must continue to polish them in order to become an effective programmer in the future. Though there are several things to focus on, one area in particular that you must emphasise is the world of data structures. Data structures, in general, are unique techniques to solving issues that use the least amount of computer resources. There are a variety of data structures that you can study and use in general. To keep things easy, we’ll start with some basic programmes that you’ll need to master before moving on to more advanced algorithms. So today let us start with How to Reverse a Number in java using While loop.

 

What’s The Approach?

 

  • Import the java.util package into the class.

 

  • Now within the main method create a new object of Scanner class,

 

  •  for example,  Scanner sc=new Scanner(System.in);

 

  • Use the Scanner class to get the input from the user.

 

  • Create A while loop that executes till the value of the number entered by the user is greater than zero.

 

  • Store that extracted digit to the reversed number variable multiply it by 10 after every iteration and add the newly extracted last digit

 

  • Update the value of the number by dividing it by 10.

 

  • End the while loop

 

  • Print the Reversed number

 

Also Read: Print Prime Factors of a Number in Java

 

Java Program to Reverse a Number Using While Loop

/*
 * TechDecode Tutorials
 * 
 * How to Reverse a number using while loop in Java
 * 
 */

import java.util.*;
public class Reverse_WhileLoop
{
    public static void main(String[] args)   
    {  
        // Creating an object of Scanner class
        Scanner sc=new Scanner(System.in); 
        System.out.print("Enter the number that is to be reversed: ");
        // taking imput from  the user
        int num=sc.nextInt();
        // integer to store reversed number
        int rev=0;
        // a While loop is being initialized 
        while(num != 0)   
        {  
            // extracts the last digit of the original number
            int last_digit = num % 10; 
            // stores and updates the reversed number after every iteration
            rev = rev * 10 + last_digit;
            //the number is updated after each iteration to remove the last digit from it
            num = num/10;  
        }  
        // printing of reversed number
        System.out.println("The reverse of the given num is: " + rev);  
    }  
}  

Input:   45587

Output:  78554

 

Leave a Reply

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