Tuesday, June 14, 2016

changeXY - Recursive - Java & C#

Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars have been changed to 'y' chars.

changeXY("codex") → "codey"
changeXY("xxhixx") → "yyhiyy"
changeXY("xhixhix") → "yhiyhiy"
Java :
1
2
3
4
5
6
public String changeXY(String str) {
  if(str.length() < 1) return "";
  char temp = str.charAt(str.length()-1);
  if(temp == 'x') temp = 'y';
  return changeXY(str.substring(0,str.length()-1))+temp;
}

Test Result:

C#:
1
2
3
4
5
6
7
public static String changeXY(String str)
        {
            if (str.Length < 1) return "";
            Char temp = str[str.Length - 1];
            if (temp == 'x') temp = 'y';
            return changeXY(str.Substring(0, str.Length - 1)) + temp;
        }

Test Result :

No comments:

Post a Comment