Search code examples
recursionpalindrome

Program returns 0 but only to "one up" in recursion, but I want it to go to the "very top"? Is this possible?


I'm new to using recursion and I'm trying to get my palindrome program to work. This is what I am trying to do: if a character is not equal, I return 0. If not, I keep recursing while increasing the i and decreasing the j. If the i is no longer less than the j, i want to say that the recursion is done, so I want to return that the word is a palindrome (=1).

But when I input a word that is not a palindrome, I correctly return a 0. (I can see this when I debug). But-- then at the end, it also returns a 1. I assume this has something to do with the fact that recursion means that the program keeps going, and the 0 gets returned to something I had previously been doing before. But- I want the 0 to go to the very top.

Is there some way around this problem? Or am I doing something wrong? Sorry if this is really basic. Thanks in advance. Here is my code:

public static int checkIfPalindrome(String s, int i, int j) {

    if (i<j) {

        if (s.charAt(i) == s.charAt(j)) {
            checkIfPalindrome(s, i+1, j-1);

        }
        else {
            return 0; 
        }
    }
    return 1;

}

Solution

  • Once you know your pointers haven't collided, and the characters they point to are the same, then the return value of this method is the return value of the recursive call. I've fixed your code to do this below but I have also reorganized it a different way, as there are other ways to go about the problem:

    public static int checkIfPalindrome(String s, int i, int j) {
    
        if (i >= j) {
            return 1;
        }
    
        if (s.charAt(i) != s.charAt(j)) {
            return 0;
        }
    
        return checkIfPalindrome(s, i + 1, j - 1);
    }