How to reverse number in Java?

UPDATED: 24 December 2014
How to reverse number in Java

Its one of the tricky program asked in Java interviews. Its very simple program however at that time our mind start thinking about some complex logic to crack the code. But its very simple logic that we uses in our day to day life and can be done with few lines. Lets see how you can do that so it will help you whenever you face this question.

Modulo Operator
Yeah you got it right. You can use number % 10 to get the last digit in number.

Source Code
/**
 * @author javaQuery
 * Reverse number in Java using Modulo Operator
 */
public class ReverseNumber {
    public static void main(String[] args) {
        int number = 123;
        int remainder;
        while(number > 0){
            remainder = number % 10;
            number = number / 10;
            System.out.print(remainder);
        }
    }
}

//Output
//321


0 comments :