C++ 回文 boolean 函数(使用指针)

标签 c++ function boolean palindrome

如何在 C++ 中创建回文函数?我正在使用 2 种函数类型(bool 和 void)。 到目前为止,这是我的代码(我真的很感激任何帮助,为什么我的代码不起作用?)谢谢!

#include <iostream>
#include <cctype>
#include <cstdlib>
#include <string>
using namespace std;


void reverse(char *);  
bool isPalindrome(char *);  

int main()  
{  
    char a[10];  
    cout << "string ";  
    cin.getline(a, 10);  
    if (palindrome(a))  
        cout << "true";   
    else  
        cout << "false";  
    return 0;  
}  
void reverse(char *s)  
{  
    char *point = s;  
    int i, min;  
    for (i = 0; *point != '\0'; i++)  
        point++;  
        min = i;  
        point--;  
    for (i = min; i > 0; i--)  
   {  
        cout << *point--;  
   }  
}  
bool ispalindrome(char *s)  
{  
    bool status;  
    char *original = s;  
    char *point = s;  
    reverse(point);        
    for (int i = 0; point != '\0'; i++)  
    {  
        if (point[i] == original[i])  
        status = true;  
        else  
        status = false;  
    }  
    return status;  
}

最佳答案

你不需要反转字符串来检查它是否回文。

算法的工作原理如下:

获取字符串的长度;
从零到字符串长度循环 2;
将位置循环计数上的字符与长度减去循环计数减1进行比较;
如果不相等则不是回文;
如果循环结束,它是一个回文;

例如:“测试”:
第一步:比较't'和't'
第二步:比较 'e' 和 's' --> 不是回文

例如“palap”:
第一步:比较'p'和'p'
第二步:比较'a'和'a'
第三步:比较'l'和'l'
现在我们知道这是一个回文。

试试这个:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int palindrom(char * s){
  int i;
  int l = strlen(s);
  for(i=0;i<=l/2;i++)
    if(s[i]!=s[l-i-1]) return 0;
  return 1;
}

int main(void) {
  char * test = "test";
  char * pal = "palap";
  printf("%s %d", test, palindrom(test));
  printf("%s %d", pal, palindrom(pal));
  return 0; 
}

关于C++ 回文 boolean 函数(使用指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22361865/

相关文章:

c++ - 为什么要在控制台的第二行输入?

c++ - 无法编译mysql源码

c++ - 检测移除打开的串口设备(Qt/Windows)

function - Play 2.0 可重用模板功能与 HTML 正文

java - FlightInformation 上的语法错误

c++ - 不移动就不能从函数返回 std::unique_ptr

javascript - 定期调用javascript函数

java - 准备一组可以传递给 java 中的函数的参数

python - 如何加速 boolean 算法

bash - 从 Bash 函数返回 boolean 值