Thursday, April 19, 2012

Java program to reverse a number - Example tutorial

How to reverse a number in Java without using any API or write a simple Java program to reverse a number is common programming questions asked on fresher level software engineer interviews. Reversing a number is also popular homework questions on many Java programming courses on school, colleges and training institutes. I personally feel java program to reverse number is good programming exercise for some one who is just started learning programming in Java or any other programming language because of its simplicity and little bit of trickiness which shows how to use operators for programming purposes rather than arithmetic purpose. In last couple of Java programming tutorial we have seen some basic programming exercises like how to reverse string in Java using recursion and how to check if a number is prime or not, while in this Java tutorial we will see a simple example of Java program to reverse number by just using basic Java operators like division operator(/) and remainder operator(%). division operator returns quotient while modules or remainder operator % returns remainder.

If you are looking for theoretical java interview question which involves understanding of concept rather than programming then you may like Why multiple inheritance is not supported in Javawhy wait and notify are defined in object class and Why main method is public static in Java. But I would say you better horn your programming skills as well by programming Simple programs than moving to tougher one which involves data-structure and designs like how to find length of linked list using iteration and recursion and  design and code for vending machine in Java which accepts per-defined coin and return per-defined product handling all practical condition like returning change, returning money if product is not there etc

How to reverse number in Java - Example

How to reverse number in Java program with exampleHere is complete code example of reversing number in Java without using any API method. This simple Java program just uses basic programming concept like loops and operators to reverse number. After each iteration you have number with one digit less than original one, same time reverse number got that last digit as there first digit. Worth noting point is multiplication of 10 which is required to move places in decimal numbers.

import java.util.Scanner;

/**
 * Simple Java program to reverse a number in Java using loop and operator
 * This program also shows example of using division operator(/) and Remainder Operator(%)
 */

public class ReverseNumberExample {

    public static void main(String args[]) {
       //input number to reverse
        System.out.println("Please enter number to be reversed using Java program: ");
        int number = new Scanner(System.in).nextInt();
     
        int reverse = reverse(number);
        System.out.println("Reverse of number: " + number + " is " + reverse(number));  
   
    }
 
    /*
     * reverse a number in Java using iteration
     * @return reverse of number
     */

    public static int reverse(int number){
        int reverse = 0;
        int remainder = 0;
        do{
            remainder = number%10;
            reverse = reverse*10 + remainder;
            number = number/10;
         
        }while(number > 0);
     
        return reverse;
    }

}

Output:
Please enter number to be reversed using Java program:
1234
Reverse of number: 1234 is 4321



That's all on how to reverse a number in Java program. This simple Java program can also be used to check if a number is palindrome or not. As a palindrome is a number whose reverse is equal to original number. If you like to practices recursion than try coming out of recursive way of reverse a number in Java, to get your hand going with recursion you can check rather intuitive example of calculating factorial of a number in Java using recursion.


Other Java Programming tutorials you may like

14 comments :

Jan Ettles said...

As this code is only dealing with integers, would it not be simpler to leave it as a String and reverse that?

public String reverse(String s) {
if (s.length() <= 1) {
return s;
}
return reverse(s.substring(1, s.length())) + s.charAt(0);
}

Then parseInt if a numeric is actually needed.

Javin @ String to int conversion java said...

@Jan, you are right on your part, you can reverse number by treating them as String in Java but this programming exercise is meant to do it without any API method and with just arithmetic operator in order to apply some kind of logic but no doubt it can be done by converting String to integer and using your solution.

Jan Ettles said...

Yeah, it's going to be tough to write something _without_ touching the API at all.
In your example, just reading in the String to be converted to an int and then reversed requires the Scanner to read and the nextInt() to translate the next token to an int.

Javin @ String to double in Java said...

Yes Jan, It's converting String input to int but that's the easiest way to get input from User, Though you can also use JOptionPane to display input dialog to input numbers but I stick to simpler one.

Rob Foster said...

Great question! Here's a solution that also handles negative numbers and overflows.

public class Reverse {
public static long reverse(int number) {
long reverse = 0;
while (number != 0) {
reverse = (reverse * 10) + number % 10;
number /= 10;
}
return reverse;
}
}

Madhan said...

Your blog is very good!

But, for this program, we would get wrong output if the input integer ends with "0". So instead of saving the remainder in to a int, instead we could use a string buffer and append it. Finally showing the stringbuffer as final ouput would be one option.

Rob Foster said...

Define wrong output. Wouldn't 12,300 reversed be 00,321 or simply 321?

Madhan said...

Hi Rob,
I understand the question as 'literal' reversal of number in which case we would be missing the zero's at the end. If we just consider the actual integer value after reversal, what you said is right.

Anonymous said...

is there a way to do this without the use of loops, if statements and strings?

Moksh said...

package reversedigit;

import java.util.Scanner;

class ReverseDigit {


public static void main(String[] args)
{
int c,a=0,b=0;
System.out.println("Enter Digit to Reverse It");
Scanner sc = new Scanner(System.in);
c=sc.nextInt();

System.out.println("Reverse Order of " + c+" is");

{


b = c%10;
a = a*10 + b;
c = c/10;
if (c > 0);

{
System.out.println(+a+""+c);
}
}
}
}

Anonymous said...

how to apply this logic for 3 digit number

Javin @ abstract class vs interface java said...

@Anonymous, This should work on any number of digit? are you facing any issue?

Bhavesh Kukreja said...

how we reverse 3 digit no. & not more than 3 digit no. is reverse and not less than 2 digit no. in java

Code Nirvana said...

Nice post friend!
but there's a ERROR in the above code, which make it UNABLE to REVERSE a huge list of NUMBERS.....

*ERROR: when i entered 120 its output came out -> 21 only. so its not giving right output for the numbers ending with ZEROS(0) like 100,1500 etc.

I corrected the CODE and HERE it is :
http://www.codenirvana.in/2013/10/JAVA-Reverse-Number-Program.html

-Thanks!

Post a Comment