Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want my 2nd if-statement to do a recursion-type loop but it is not returning anything and defaulting to false, what am i doing wrong?

bool isPalindrome(string some_string) {
    if (some_string.length() == 0 || some_string.length() == 1) {
        return true;
    }

    if (some_string[0] == some_string[some_string.length() - 1]) {
        return isPalindrome(some_string.substr(1, some_string.length() - 1));
    }

    else {
        return false;
    }
}

First off, this code is to check if a string is palindrome or not. I looked up some links and thought I could use substr to get the characters after the first index and before the last character index, what am I doing wrong? This is my first time here so I’m sorry if this question was not well initiated.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem with your code is that substr() is being used in the wrong way. Here’s a link to cppreference with full doc about this method. But in simple words, the problem is that the second argument of this method isn’t the last index of the substring, but is the number of characters that should be included in the substring. So, in your second if, you call recursion with the same string, but without the first letter. So, for the string "abba", it will execute isPalindrome("bba") instead of isPalindrome("bb").

To do what you intended to do, you have to change this line:

return isPalindrome(some_string.substr(1, some_string.length() - 1));

to this instead:

return isPalindrome(some_string.substr(1, some_string.length() - 2));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading