Sunday 3 May 2015

Java program to reverse number

Java program to reverse number

Reverse a number is good interview question.


import java.util.Scanner;
public class ReverseNumber {
    public static void main(String[] args) {
          Scanner sc=new Scanner(System.in);
          System.out.println("Enter Number");
          int num=sc.nextInt();
          System.out.println("Reverse Number="+doReverseNumber(num));
    }
   
    private static int doReverseNumber(int num){
        int reverseNum=0;
        while (num>0) {
            reverseNum=reverseNum*10+(num%10);
            num/=10;
        }       
        return reverseNum;
    }
}

Output:

Enter Number
123
Reverse Number=321

+++++++++++++++++++

Enter Number
120
Reverse Number=21

++++++++++++++++++++

Enter Number
054
Reverse Number=45


No comments:

Post a Comment