For example, we could write a recursion to reverse a string from "ABC" to "CBA".
// Parameter: A string.
// Return: Last character of the string.
function reverseString(p_val){
// Get the string's length
var length = p_val.length;
// Get the last character
var lastchar = p_val.charAt(length - 1);
if (length == 1) {
// Return the last char
return lastchar;
} else {
// Run the recursion
return lastchar + reverseString(p_val.substring(0,length - 1))
}
}
Let's say the parameter is "ABC". The process will be:
- Return: C + reverseString("AB")
- Return: C + B + reverseString("A")
- Return: C + B + A
No comments:
Post a Comment