Thursday, October 9, 2014

Reverse String (recursive)


public class ReverseStringTest {
   
    public String reverseString(String str){
       
        // str.substring(0,2) returns index of 0 and 1 of str
        return (str.length()==1? str: str.charAt(str.length()-1) + reverseString(str.substring(0,str.length()-1)));
       
    }
   
    public static void main(String[] args){
        ReverseStringTest rst = new ReverseStringTest();
        System.out.println(rst.reverseString("abcd"));
    }

}


OUTPUT:
dcba

No comments:

Post a Comment