Wednesday, September 20, 2023

Java Program to Reverse an Integer 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 question on many Java programming courses in schools, colleges, and training institutes. I personally feel java program to reverse number is good programming exercise for someone who is just started learning to program in Java or any other programming language because of its simplicity and a 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 a 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 modulus or remainder operator % returns the remainder.

If you are looking for a theoretical java interview question that involves an understanding of concept rather than programming then you may like Why multiple inheritances is not supported in Javawhy to wait and notify are defined in object class, and Why the 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 the length of linked list using iteration and recursion and  design and code for the vending machine in Java which accepts pre-defined coin and returns pre-defined product handling all practical condition like returning the change, returning money if the product is not there, etc


How to reverse a number in Java - Example

How to reverse number in Java program with exampleHere is a complete code example of a reversing number in Java without using any API method. This simple Java program just uses basic programming concepts like loops and operators to reverse numbers. After each iteration, you have a number with one digit less than the original one, same time reverse number got that last digit as there first digit. 

Worth noting point is a 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 a Java program. This simple Java program can also be used to check if a number is a palindrome or not. As a palindrome is a number whose reverse is equal to the original number. 

If you like to practices recursion than try coming out of the recursive way of reverse a number in Java, to get your hand going with recursion you can check rather an intuitive example of calculating factorial of a number in Java using recursion.


Other Java Programming tutorials you may like

And now is the quiz time, What is the time complexity of this algorithm to reverse a give integer number? can you improve this by using any data structure or different approach?

26 comments :

Unknown 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.

Unknown 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.

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.

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?

Unknown said...

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

Udit 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!

Unknown said...

how to reverse a number like 10,100,500,1000.............etc

Naveen KTR said...

how to solve if integer starting with zero??? (ex. 0321, 042)

Jitendra Mohanty said...

How can I reverse a number without using any loop?

Unknown said...

Write an object oriented java program to display the arithmetic operation reverse of a number using switch case

Plzzzzzz give me this program fast

One23drumm said...

How about this?
Integer.parseInt(new StringBuilder(String.valueOf(number)).reverse().toString())

javin paul said...

Hello One23drumm, that's valid solution but will not be accepted in most of the interview because they want you to solve without using Java framework methods like reverse(). Try solving by using your own logic and without reverse method.

mrunal said...

how to reverse negative numbers? example -100 to -001 or -5461 to -1645?

javin paul said...

Hello mrunal, isn't following the same method will work? just replace + with - to add into a negative number.

Unknown said...

I want to display as number should be positive when it's less than zero while reverse the number???what's the code

javin paul said...

you can check positive and negative number like greater than zeor or less than zero, or you can use bitwise operator, check this article, how to check if number is positive or negative in Java for some code examples.

Anonymous said...

I need recurring method of this reverse

javin paul said...

Hello Anonymous, do you mean recursive method? I have never heard of recurring method but if you mean how to solve this problem using recursion, just replace the code in the loop into recursive call. If you find it difficult, I can add that into code as well.

Anonymous said...

static int result =0;
static int reverse(int n){
if(n==0){
return 0;
}
int rem = n%10;
result = result*10+rem;
reverse(n/10);
return result;
}

Krishna said...

public class NumberReverseRecursion {

public static String reverse(int num, String rev) {

if (num == 0)
return rev;
rev = rev + num % 10;
return reverse(num / 10, rev);
}

public static void main(String[] args) {
System.out.println("Enter the number : ");
Scanner sc = new Scanner(System.in);
String rev = "";
int n = sc.nextInt();
System.out.println(Integer.valueOf(reverse(n, rev)));
}
}

Post a Comment