Monday, 18 August 2014

How to reverse a number in Java

Reverse a number/Integer



We can reverse a number by converting it into a String or iteratively or recursively.
Now we will how to reverse  number by converting it into a String.





package com.interviewCodes.String;

public class ReverseNumberDemo1 {
      
       public static void main(String[] args) {
              int num=12456;
              //converting Integer into a String
              String str=String.valueOf(num);
              //Now we can reverse the String as shown in my previous post
              //And then convert that String into Integer like below
              Integer revNum=Integer.parseInt(str);
       }

}

We can reverse the Number by iteratively or recursively as below:

package com.interviewCodes.String;

import java.util.Scanner;

public class ReverseNumberDemo{

       public static void main(String[] args) {
               
         int num, reverseNum = 0;
      System.out.println("Enter the number to reverse");
      Scanner in = new Scanner(System.in);
      num = in.nextInt();
      //reverse a number iteratively
      reverseNum=reverseIteratievly(num);
      System.out.println("Reverse a number Iteratively : "+reverseNum);
      //reverse a number recursively
      reverseNum=reverseRecursievly(num);
      System.out.println("Reverse a number Iteratively : "+reverseNum);
    }
       public static int reverseIteratievly(int num) {

              int reverse=0;
           while( num != 0 )
             {
                 reverse = reverse * 10;
                 reverse = reverse + num%10;
                 num = num/10;
             }
             return reverse;
       }
    public static int  reverseRecursievly(int num) {
             
       return _reverseRecurievly(num,0);
     }

     public static int _reverseRecurievly(int n,int r){
       if(n==0){
              return r;
       }
       else{
              return _reverseRecurievly(n/10,r*10+n%10);
       }
}

}

That's all about reverse a number.If any other ways are there to reverse a number,please comment.Thanks for reading.

No comments:

Post a Comment

How to find the String that contains only alphabets

Today we will see how to  find list of Strings that contains only alphabets. In this post I did this with and without using regular expres...