Sunday, 2 October 2011

4.6-4.9


4.6
public static String getReverse(String word)
    {
    String str = "";
    for (int i = 0; i<word.length(); i++)
    {
       str += word.substring(word.length()-i-1, word.length()-i);
    }
    return str;
    }//getReverse

    //uses recursion to reverse word
    public static String getReverseRecursive(String word)
      {
     if (word.length()==1)
     {
           return word;
     }
     else
     {
       String str = word.substring(word.length()-1) + getReverseRecursive(word.substring(0, word.length()-1));
       return str;
    }
    }//getReverseRecursive


4.7
            The advantage of using an iterative approach for me is the logic, it makes much more sense for me to go through something in a linear fashion, or rather simply not backwards as you do in recursion. On the other hand, using a recursive approach is much more efficient as it doesn't use any loops, and simple uses some commands and calls. Essentially, if you can think of the solution recursively it's much more effective, but it's very hard to do so for me, in respect with an iterative approach.

4.8
public static boolean isPalindrome(String word)
    {
        if(word.length()%2 == 0)
             return(word.substring(0,word.length()/2) == getReverse(word.substring(word.length()/2, word.length())));
        else return(word.substring(0,word.length()/2) == getReverse(word.substring(word.length()/2+1, word.length())));
    }
}//class StringReverseDemo

4.9
I actually forgot the meaning of static and non-static, I'll ask about it in class.

No comments:

Post a Comment