Java program to reverse a given number

Java program to reverse a given number thumbnail
8K
By Dhiraj Ray 01 January, 2018

Description

Write a java program to reverse a given number by using only numeric operators.Suppose, if you are given an input of 4567 then the output should be 7654.In the program below, we have only used the modulus or remainder and / operator.Following is the complete program.

ReverseNumber.java
package com.devglan;

public class ReverseNumber {

    public int reverseNumber(int number){

        int reverse = 0;
        while(number != 0){
            reverse = (reverse*10)+(number%10);
            number = number/10;
        }
        return reverse;
    }

    public static void main(String a[]){
        ReverseNumber reverseNumber = new ReverseNumber();
        System.out.println("Reversed Number: " + reverseNumber.reverseNumber(3579));
    }
}

Explanation

By using modulus operator(%) on the input int by 10 will extract off the rightmost digit. example: (1234 % 10) = 4.Multiplying an integer by 10 will "push it left" exposing a zero to the right of that number, example: (5 * 10) = 50.Dividing an integer by 10 will remove the rightmost digit. (75 / 10) = 7

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.