Friday, 20 December 2013

How to reverse Strings and Integers

Strings Reversal

First Lets looks at how can we reverse a String in Java. We can do it two ways

  1. Iterative way
  2. Recursive way 
Both ways are given in the following code

/**
 * Created with IntelliJ IDEA.
 * User: aniket
 * Date: 20/12/13
 * Time: 2:53 PM
 */
public class StringReverser {

    public static String iterativeReverse(String originalString){

        char[] originalStringCharacterArray = originalString.toCharArray();
        StringBuilder reversedString = new StringBuilder();
        for(int i=originalString.length()-1;i>=0;i--){
            reversedString.append(originalStringCharacterArray[i]);
        }
        return reversedString.toString();
    }

    public static String recursiveReverse(String originalString){

           if(originalString.length() == 1){
               return originalString;
           }
            else {
               return recursiveReverse(originalString.substring(1)) + originalString.charAt(0);
           }
    }

    public static void main(String args[]){

        String originalString = "abcdef";

        System.out.println("Revered String by iterative way is : " + StringReverser.iterativeReverse(originalString));
        System.out.println("Revered String by iterative way is : " + StringReverser.recursiveReverse(originalString));

        // For Palindrome simply reverse the String and use .equals()

    }

}
 
Output : 
Revered String by iterative way is : fedcba
Revered String by iterative way is : fedcba

For Palindrome you can simply use the above code to get the reversed String and check both using String's .equals() method.

Integer Reversal

Integers reversal is again very easy. You simply should know proper use of % and / operators.


/**
 * Created with IntelliJ IDEA.
 * User: aniket
 * Date: 20/12/13
 * Time: 4:45 PM
 */
public class NumberReverser {

    public static int reverseNumber(int number){

        int reverse = 0;
        while(number != 0){
            reverse = (reverse*10) + (number%10);
            number = number/10;
        }
        return reverse;
    }

    public static void main(String args[]){
        System.out.printf("Reverse of number 1234 is : " + NumberReverser.reverseNumber(1234));

    }

}
Output : 

Reverse of number 1234 is : 4321

No comments:

Post a Comment

t> UA-39527780-1 back to top