簡體   English   中英

c++ 中的簡單回文

[英]Simple Palindrome in c++

有人會好心地告訴我如何用這個回文檢查器得到正確的結果嗎?

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

對於初學者,請確保將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;

這將是一個簡單的方法:

#include <algorithm>
#include <string>

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

關於您的代碼,如果任何一個元素不匹配,則必須返回false 如果所有元素都匹配,則應返回true 當前,每當字符串的長度不為0時,您都將返回true ,因為您正在比較索引ij ,而不是元素。 您需要更改邏輯:

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;

還要注意,您不必遍歷元素的總數,只需迭代一半即可。 但是我建議使用標准庫。 從上面的示例可以看出,使用標准庫算法時,引入錯誤比較困難。

嘗試這個。 這個對我有用。

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