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"
Java :
1 2 3 4 5 6 7 | public String changePi(String str) { if (str.length() < 1) return ""; int index = str.indexOf("pi"); if (index < 0) return str; String temp = str.substring(0, index); return temp+"3.14"+changePi(str.substring(index+2, str.length())); } |
Test result:
C# :
1 2 3 4 5 6 7 8 9 | public static String changePi(String str) { if (str.Length < 1) return ""; int index = str.IndexOf("pi"); if (index < 0 ) return str; String temp0 = str.Substring(0, index); String temp = str.Substring(index+2, str.Length-(2+index)); return temp0+"3.14" + changePi(temp); } |
Test Result :
No comments:
Post a Comment