10-21-2013

posted Oct 21, 2013, 8:43 AM by Samuel Konstantinovich   [ updated Oct 22, 2013, 9:10 AM ]
1. reverseF(String s) takes a non-empty String s and returns a string with its letters placed in the reversed order. Use a FOR loop.
e.g.,
reverseF(“stressed”) → “desserts”
reverseF(“racecar”) → “racecar”

2. reverseR(String s) takes a non-empty String s and returns a string with its letters placed in the reversed order. Use recursion.
reverseR(“stressed”) → “desserts”
reverseR(adogapanicinapagoda”) → “adogapanicinapagoda

Solutions:

public class TestStrings{
    public static String reverse(String s){
String ans = "";
for(int i = 0; i < s.length(); i++){
   ans = s.charAt(i) + ans;
}
return ans;
    }
    public static String reverseR(String s){
if(s.length() < 2){
   return s;
}else{
   //return reverseR(s.substring(1,s.length())) + s.charAt(0);
   return reverseR(s.substring(1)) + s.charAt(0);
}
    }

    public static void main(String[]args){
System.out.println(reverse(reverseR("Hello")));
    }
}


Comments