用C++写一个回文数判定
时间: 2023-04-10 16:01:50 浏览: 114
好的,以下是用C语言写的回文数判定代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, j, len, flag = 1;
printf("请输入一个字符串:");
scanf("%s", str);
len = strlen(str);
for (i = 0, j = len - 1; i < len / 2; i++, j--) {
if (str[i] != str[j]) {
flag = 0;
break;
}
}
if (flag) {
printf("%s是回文数\n", str);
} else {
printf("%s不是回文数\n", str);
}
return 0;
}
```
希望能对您有所帮助!
相关问题
用c++编写一个回文是指正读和反读均相同的字符序列,如”abba”和”abdba”均是回文,但”good”不是回文,试写一算法利用栈判定给定的字符序列是否为回文。(提示:将一半字符入栈)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int top;
} Stack;
void InitStack(Stack *S) {
S->top = -1;
}
int StackEmpty(Stack S) {
return S.top == -1;
}
int StackFull(Stack S) {
return S.top == MAXSIZE - 1;
}
int Push(Stack *S, char x) {
if (StackFull(*S)) {
return 0;
}
S->data[++S->top] = x;
return 1;
}
char Pop(Stack *S) {
if (StackEmpty(*S)) {
return '\0';
}
char x = S->data[S->top--];
return x;
}
int Palindrome(char *str) {
Stack S;
InitStack(&S);
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
Push(&S, str[i]);
}
int j;
if (len % 2 == 0) {
j = len / 2;
} else {
j = len / 2 + 1;
}
while (j < len) {
char x = Pop(&S);
if (x != str[j]) {
return 0;
}
j++;
}
return 1;
}
int main() {
char str[MAXSIZE];
printf("请输入一个字符串:");
scanf("%s", str);
if (Palindrome(str)) {
printf("是回文。\n");
} else {
printf("不是回文。\n");
}
return 0;
}
试写一个程序判定给定的字符向量是否为回文,用栈实现。
以下是一个C++程序,使用栈来判断给定的字符向量是否为回文:
```c++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
bool isPalindrome(vector<char>& chars) {
stack<char> s;
int n = chars.size();
int mid = n / 2;
for (int i = 0; i < mid; i++) {
s.push(chars[i]);
}
if (n % 2 == 1) {
mid++;
}
for (int i = mid; i < n; i++) {
if (s.top() != chars[i]) {
return false;
}
s.pop();
}
return true;
}
int main() {
vector<char> chars = {'a', 'b', 'c', 'b', 'a'};
if (isPalindrome(chars)) {
cout << "The vector is a palindrome." << endl;
} else {
cout << "The vector is not a palindrome." << endl;
}
return 0;
}
```
该程序中,isPalindrome()函数接收一个字符向量chars作为参数,使用栈来判断该向量是否为回文。首先,将前一半的字符压入栈中,然后从中间位置开始检查向量的剩余部分,与栈中的字符进行比较,如果有不同的字符,立即返回false。注意,在向量的长度为奇数的情况下,中间位置的字符不需要比较,因此需要先将mid设为(n / 2),最后如果向量长度为奇数,将mid自增一位。
在主函数中,定义一个字符向量,将其传递给isPalindrome()函数,并打印出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)