Found the following test on http://thedailywtf.com. It tickled my fancy. An interesting use for recursion.
Question 1 (a) What does the following function do? (b) How could the function be improved? (c) Rewrite the function with your suggested improvements.
public String funcX (String s) {
if (s == null || s.length() == 1 || s.length() == 0) {
return s;
} else {
return funcX(s.substring(1)) + s.substring(0, 1);
}
}
if (s == null || s.length() == 1 || s.length() == 0) {
return s;
} else {
return funcX(s.substring(1)) + s.substring(0, 1);
}
}
Just a small javadoc addendum to clarify things:
- public String substring(int beginIndex, int endIndex)
- Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
public String funcX (String s) {
ReplyDeletereturn aString != null && aString.length() != 1 | aString.length() != 0 ? new StringBuffer(aString).reverse()
.toString() : null;
}
Correct!
DeleteIt is basically a really complicated form of Stringbuffer.reverse.
I have also put up a java developer test with scoring assessment. let me know how you find it.
ReplyDelete