Java > Recursion-1 > changePi (CodingBat Solution)

Problem:

Given a string, compute recursively (no loops) a new string where all appearances of "pi" have been replaced by "3.14".

changePi("xpix") → "x3.14x"
changePi("pipi") → "3.143.14"
changePi("pip") → "3.14p"


Solution:

public String changePi(String str) {
  if (str.equals("") || str.length() < 2) return str;
  if (str.charAt(0) == 'p' && str.charAt(1) == 'i') 
    return "3.14" + changePi(str.substring(2));
  return str.charAt(0) + changePi(str.substring(1));
}


6 comments :

  1. if (str.equals("") || str.length() < 2) return str;

    it should be:
    if (str.equals("") || str.length() < 2) return newStr+str;

    ReplyDelete
    Replies
    1. No, it should be
      if(str.length() < 2) return str;

      Delete
  2. public String changePi(String str) {
    if(str.length() < 2) return str;
    if(str.substring(0, 2).equals("pi")) return "3.14" + changePi(str.substring(2));
    return str.charAt(0) + changePi(str.substring(1));

    ReplyDelete
  3. Thanks a lot searching for this.

    ReplyDelete
  4. public String changePi(String str) {
    int idx = str.indexOf("pi");
    if (idx==-1)
    return str;

    return changePi(str.substring(0,idx)+"3.14"+str.substring(idx+2));
    }

    ReplyDelete
  5. public String changePi(String str) {
    if(str.equals(""))
    return str;
    else if(str.startsWith("pi"))
    return "3.14"+changePi(str.substring(2));
    else return str.charAt(0)+changePi(str.substring(1));

    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact