'Simple Palindrome in c++

Would someone be kind enough to route me in the right direction regarding how to get the correct out with this palindrome checker

#include <iostream>
using namespace std;

bool isPal(string number){
    for (int i = 0, j = number.length(); i < number.length(), j > 0; i++, j--)
        if (i == j){
            return true;
        }
        else
            return false;
    }

int main(){
    cout << isPal("helleh") << "\n";
        cout << isPal("9009") << "\n";
    system("pause");
    return 0;
}
c++


Solution 1:[1]

This would be an easy way to do it:

#include <algorithm>
#include <string>

bool isPal(const std::string& number)
{
  return std::equal(number.begin(), 
                    number.begin() + number.size()/2,
                    number.rbegin());
}

Concerning your code, you have to return false if any one of the elements does not match. You should only return true if all elements match. Currently, you are returning true whenever the length of the string is not 0 because you are comparing indices i and j, not elements. You need to change your logic:

string::size_type len = number.length();

if (len == 0) return true; // corner case

for (string::size_type i = 0, j = len; i < len/2; i++, j--)
{
  if (number[i] != number[j-1]) return false;
}
return true;

Also note that you don't have to iterate over the whole number of elements, just one half. But I suggest using the standard library. You can see from the example above that is it harder to introduce bugs when using standard library algorithms.

Solution 2:[2]

Try this. It works for me.

bool isPal(string number)
{
   int len = number.length();
   for (int i = 0, j = len-1; j > i ; ++i, --j)
   {
      if ( number[i] != number[j] )
      {
         return false;
      }
   }
   return true;
}

Solution 3:[3]

#include <iostream>

#include <string.h>

using namespace std;

bool isPolindrome(string str) {

    long n = str.length();

    for (long i=0; i<n/2; i++) {

        if(str[i] != str[n-1-i]) return false;

    }

    return true;
}

int main() {

    string s;

    cin >> s;

    cout << boolalpha << isPolindrome(s) << endl;

    return 0;

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 R Sahu
Solution 3 ChrisMM