Palindrome Elegance
Adam La Rosa
Posted on March 29, 2020
Playing with a little C++ I eventually came across the problem of checking to see if a string of characters is a palindrome or not. Using a solution I've had success with I gave this to the compiler...
#include <iostream>
using namespace std;
int main() {
string word = "";
string test = "";
cout << "Enter something: ";
cin >> word;
for (int i = word.length() - 1; i >= 0; i--) {
test = test + word[i];
}
word == test ? cout << "Palendrome!\n" : cout << "Not.\n";
}
Like before, this did the job. I was curious though. There must be a better way to solve this problem. A quick search around provided me this gem.
bool is_palindrome(string text) {
int start = 0;
int end = text.length() - 1;
while (end > start) {
if (text[start++] != text[end--]) {
return false;
}
}
return true;
}
Right off the bat I'm liking this solution more. Where taking a word and creating a reverse of it seems like the right approach, this second solution proves it to be too labor intensive. Our while loop iterates over what should be two equal characters and compares them. As soon as two don't match, not a palindrome.
Posted on March 29, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.