FAQ: Code Challenge: C++ Functions - Palindrome

I had a look over this code once more and I realise you are correct - nice work, thanks for letting me know!

1 Like

My initial thought with this challenge was to take the first and last letter and compare them, then second letter and second last letter etc. I came to the solution below which feels pretty concise compared to where I started, but I am curious if anyone could find any ways to make it even more concise while maintaining the functionality. (I changed the return value to string to be doubly sure I was getting the correct results and not some arbitrary 1 or 0).

Look forward to any suggestions!

#include <iostream>

std::string is_palindrome(std::string text) {
      
  int reverse = text.size() - 1;

  for(int forward = 0; forward < text.size(); forward++) {
    if(text[forward] != text[reverse]) {
      return "False";
    } 
    else {
      reverse--;
    }
  }
  return "True";
}

int main() {
      
  std::cout << is_palindrome("madam") << "\n";
  std::cout << is_palindrome("ada") << "\n";
  std::cout << is_palindrome("lovelacl") << "\n";
      
}

I was doing it correctly by following the hint but your solutions seems more compact. This is one of those times that the while loop was better than the for loop.

bool is_palindrome(std::string text) {
  int end = text.size() - 1;
  int start = 0;

  while (end > start) {
    if ( text[start++] != text[end--] ) {
      return false;
    } else {
      return true;
    }
  }
}

Double check your flow here; what happens when you check the first character? What about further characters?

1 Like

I did not test this code but that’s a rather neat perspective to approach this problem.

I’m glad I wasn’t the only one who was a bit confused, I actually thought I had forgot or skipped the lesson about strings, although as someone who has prior knowledge in another coding language I knew that I could treat the string like the vector and iterate through it’s characters using square brackets string[0], however, even after doing all of this, my code was still returning false, I even printed my results and added single quotes to ensure that both strings were identical, which they are.

I already knew to google for possible solutions, but I couldn’t figure out the reason why this was happening, I tried other peoples codes and the results are correct, so I was definitly doing something wrong, I then discovered that the following bit of code returns the correct result when printed, but for some reason it was not comparable.

for(int i = 0; i <= n; i++) {
  reverseText += text[n - i];
}

/* Results::
'madam'
'madam'
0
'ada'
'ada'
0
'lovelace'
'ecalevol'
0
*/

However, changing that bit of code to the following fixed the issue.

for(int i = n; i >= 0; i--) {
  reverseText += text[i];
}
/* Results::
'madam'
'madam'
1
'ada'
'ada'
1
'lovelace'
'ecalevol'
0
*/

Obviously the latter is a better way to do this, but I thought this was strange and wanted to share in the event others had the same issue as me.

You haven’t shown all the code for your first snippet.
I suspect that in the first snippet, you have made the assignment n = text.length() or n = text.size() instead of n = text.length() - 1 or n = text.size() - 1
If you used n = text.length() with the for loop in your first snippet, then first time through the loop text[n - i] will actually try to access a non-existent character of text. It won’t raise an error and it won’t show up in your printed reverse string. But if you used a debug statement such as std::cout << reverseText.length() << "\n";, you will see that your reversed string has an extra non-visible character.

1 Like

I decided to revisit the code and you’re right, I never added the text.length() - 1, that was a good catch especially without the snippet. I actually found this strange as usually when you wrap a variable in quotes it would show a space or something to indicate that sort of issue, but with c++ it doesn’t seem to be the case, unless ofcourse we count the length of the text as you mentioned.

Thanks for responding.

1 Like

You should explain in more detail what are you questions about. You first declare an empty string. Then you do a for loop that starts in size of the argument -1 as the size will be +1 to the index (counting 0) and ending the loop at 0, that’s why the greater or equal. Then you just check if both strings are the same. The function’s type has to be bool as we’re returning true or false.

Thanks! I didn’t ask the question the right way, I apologize. I understand it a bit, I am going to continue studying the code until I understand how it works.

1 Like

Would help if even some of the code we’re supposed to use in this lesson was actually taught beforehand.

Honestly I look at everything as a learning opportunity! This just encourages me that we should go through multiple valid resources to fully understand anything, and that we also must go through a trial and error process until we understand what we are and aren’t supposed to do.

This is how I solved it. It works, but the system won’t accept this solution.
It uses the function std::reverse


#include
#include

// Define is_palindrome() here:
bool is_palindrome(std::string text1) {

std::string text2 = text1;
std::reverse(text2.begin(), text2.end());

if (text2 == text1) {
return true;
}
else {
return false;
}

}

int main() {

std::cout << is_palindrome(“madam”) << “\n”;
std::cout << is_palindrome(“ada”) << “\n”;
std::cout << is_palindrome(“lovelace”) << “\n”;

}

So here’s my solution :grin:

#include <iostream>
#include <vector>

// Define is_palindrome() here:
bool is_palindrome(std::string text)
{
  std::vector<char> vector1;
  std::vector<char> vector2;
  
  for (int i = 0; i < text.size(); i++)
  {
    vector1.push_back(text[i]);
  }
  for (int j = vector1.size() - 1; j >= 0; j--)
  {
    vector2.push_back(vector1[j]);
  }
  if (vector1 == vector2)
  {
    return true;
  }
  else
  {
    return false;
  }

}

int main() {
  
  std::cout << is_palindrome("madam") << "\n";
  std::cout << is_palindrome("ada") << "\n";
  std::cout << is_palindrome("lovelace") << "\n";
  
}

The only problem i see here is that you are using the letter “i” for both loops, you should take the good habit to use a different letter for each of your variables in your loops, as for the rest, this is almost exactly the solution i found too =D

The output will be 0, 1 if you using bool, but when using string the output will be “true”, “false”.

Hello, I haven’t seen anyone do this exercise the way I did, so could someone tell me if this solution is ok?

#include <iostream>

// Define is_palindrome() here:

bool is_palindrome(std::string text) {

  std::string originaltext = text;

  int n = text.size() - 1;

  for (int i = 0; i <= text.size() - 1; i++) {
    text[i] = originaltext[n];
    n--;
  }

  if (originaltext == text) {
    return true;
  }

  else {
    return false;
  }

}

int main() {

  std::cout << is_palindrome("madam") << "\n";
  std::cout << is_palindrome("ada") << "\n";
  std::cout << is_palindrome("lovelace") << "\n";

}

i think it would be prettier if you just write i < text.size()

the code should work in every case, not only for the arguments(the words) which were put there in int main(), if the words were different, your program wouldn’t work

This challenge can’t be completed with the concepts taught so far in the course. I’m glad I looked at this forum to confirm that I hadn’t forgotten an important lesson about reversing text strings. Unfortunately, I didn’t make it here until after spending 15 minutes re-reading every module of every lesson of every unit prior to this one on functions, as well as every page of the cheat sheet. As others have states, I would really appreciate if there was a disclaimer that these challenges will require outside research of concepts that have not been taught.