Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

2/23/2013

Recursion with palindrome example

Today I found a great example of recursion function with palindrome word.  If you don't know what is palindrome, here is a wiki quote:
palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, with general allowances for adjustments to punctuation andword dividers.
Recursion function:


// recursive function declaration

function isPalindrome(text){ if (text.length <= 1) return true;
    if (text.charAt(0) != text.charAt(text.length -1)) return false;
    return isPalindrome(text.substr(1,text.length -2));
};

Now, if try to call recursive function with some palindrome, for example madam you'll get true, and madams will return false. Inner algorithm is fun and brain teasing.

No comments:

Post a Comment