Home > front end >  Boolean Function throwing unexpected answer in C ,Can anyone Explain this
Boolean Function throwing unexpected answer in C ,Can anyone Explain this

Time:08-11

Giving Correct Answer

    bool is_palindrome(string s,int start,int end){
    while(start<=end){
        if(s[start  ]!=s[end--]){
            return false;
        }
    }return true;
} 

Giving Wrong Answer

bool is_palindrome(string s,int start,int end){
    while(start<=end){
        if(s[start  ]==s[end--]){
            return true;
        }
    }return false;
}

Please Explain If Anyone knows the Right Explanation,After Searching, I couldn't find the Appropriate justification for it.

CodePudding user response:

Your first code says

  • If there are at least two unequal characters, it is not a palindrome
  • Otherwise, it is a palindrome (i.e. when all the characters "match")

Your second code says

  • If there are at least two equal characters, it is a palindrome
  • Otherwise, it is not a palindrome (i.e. when none of the characters "match")

If you can't see the difference between them, I suggest you think about it until you do; negation is much trickier than people think.

Another way to see the problem is to notice that in order to be sure that something is a palindrome, you must look at all the characters, so you can't return true before you have done that.
On the other hand, in order to be sure that something isn't a palindrome, you only need to find a single mismatch, so you can return false as soon as you do.

CodePudding user response:

your second code returns true even if only two characters match, like asda will return true but it's not a palindrome neither is bssw but it returns true. You need to compare every characters, if you want to do in the second way then:

bool is_palindrome(string s,int start,int end){
    while(start<=end){
        if(s[start  ]==s[end--]){
            continue;
        }
        else { 
            return false;
       }
    }
    return true;
}

  • Related