I was making a simple palindrome checker and can't understand why the iterator works with index 0, but won't work with index -1, you can see that both codes print the SAME text, but not the same boolean.
Can anyone explain me what's the logic behind this?
The only different part on both codes is this:
for(int i=text.size();i>=-1;i--) Not Working
for(int i=text.size()-1;i>=0;i--) Working
WORKING:
#include <iostream>
// Define is_palindrome() here:
std::string is_palindrome(std::string text){
std::string reverse= "";
for(int i=text.size()-1;i>=0;i--){
reverse += text[i];
}
if(reverse == text){
return text + " IS palindrome (reverse text: " + reverse +")";
} else {
return text + " NOT palindrome (reverse text: " + reverse + ")";
}
}
int main() {
std::cout << is_palindrome("madam") << "\n";
std::cout << is_palindrome("ada") << "\n";
std::cout << is_palindrome("lovelace") << "\n";
}
output
madam IS palindrome (reverse text: madam)
ada IS palindrome (reverse text: ada)
lovelace NOT palindrome (reverse text: ecalevol)
NOT WORKING
#include <iostream>
// Define is_palindrome() here:
std::string is_palindrome(std::string text){
std::string reverse= "";
for(int i=text.size();i>=-1;i--){
reverse += text[i];
}
if(reverse == text){
return text + " IS palindrome (reverse text: " + reverse +")";
} else {
return text + " NOT palindrome (reverse text: " + reverse + ")";
}
}
int main() {
std::cout << is_palindrome("madam") << "\n";
std::cout << is_palindrome("ada") << "\n";
std::cout << is_palindrome("lovelace") << "\n";
}
output
madam NOT palindrome (reverse text: madam)
ada NOT palindrome (reverse text: ada)
lovelace NOT palindrome (reverse text: ecalevol)