class Solution {
public:
bool isPalindrome(int x) {
std::string s = std::to_string(x);
bool returnthis = false;
for (int i=0;i<s.size();i++){
for (int j=s.size()-1;j>=0;j=j-1){
if (s[i]==s[j]){
bool returnthis = true;
}
}
}
return returnthis;
}
};
i am trying to solve the palindrome question using strings but in my code, returnthis boolean never becomes true. why can that be? (i know there are better solutions to this probably but i am a beginner and all i could think of was this solution)
You are trying to compare each character of the string with every other character from the end, which is not the correct approach for checking a palindrome. A palindrome string is a string that reads the same backward as forward. Therefore, you only need to check if the first character is equal to the last, the second is equal to the second last, and so on, up to the middle of the string.
Moreover, you've declared a local variable
returnthisinside the if statement, which shadows thereturnthisvariable defined at the beginning of the function. This innerreturnthisis not the same variable as the one you return at the end of your function. The value of the outerreturnthisnever changes and remainsfalse.Instead, try defining your two pointers,
iandj, outside a while loop and using them to compare characters from the start and the end of the string, moving towards the center and simply returning the appropriate boolean directly.