简体   繁体   English

c++ 中的简单回文

[英]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;
}

For starters, make sure you initialize j to number.length() - 1. Doing straight length will make you go out of bounds since we start counting at 0. Also, (i == j) is comparing the indices i and j, not the elements. 对于初学者,请确保将j初始化为number.length()-1。因为从0开始计数,所以直线长度会使您超出范围。而且(i == j)正在比较索引i和j,不是元素。

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

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. 关于您的代码,如果任何一个元素不匹配,则必须返回false You should only return true if all elements match. 如果所有元素都匹配,则应返回true Currently, you are returning true whenever the length of the string is not 0 because you are comparing indices i and j , not elements. 当前,每当字符串的长度不为0时,您都将返回true ,因为您正在比较索引ij ,而不是元素。 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. 从上面的示例可以看出,使用标准库算法时,引入错误比较困难。

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;
}
#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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM