C/C++ Programming Learning-Week 10② Palindromes _easy version

Topic link

Title description

"Palindrome string" is a string that reads both forward and backward, such as "level" or "noon", etc., which are palindrome strings. Please write a program to determine whether the string read is a "palindrome".

Input
contains multiple test instances. The first line of the input data is a positive integer n, which represents the number of test instances, followed by n strings.

Output
If a string is a palindrome, output "yes", otherwise output "no".

Sample Input

4
level
abcde
noon
haha

Sample Output

yes
no
yes
no

Ideas

Determine whether the input string is a palindrome. That is to see whether the string is symmetrical, we can compare the first character and the last character, the second character and the penultimate character... to see if they are all equal, if they are equal, it means a palindrome, otherwise, Not a palindrome.

Here, I wrote two functions, one is to determine whether a number is a palindrome, and the other is to determine whether a string is a palindrome. Or use the strrev() function char *strrev(char *str);to reverse the string. The prototype is: str is the string to be reversed.

Determine whether a number is a palindrome:

void Is_Number_Palindrome(int num)	//判断一个数是否为回文数
{
    
    
	int y = 0, s = num;
	while(s > 0)
	{
    
    
		y = y * 10 + s % 10;
		s = s / 10;
	}
	y == num ? printf("%d回文\n", num) : printf("%d不回文\n", num);
}

Determine whether a string is a palindrome:

void Is_String_Palindrome(char a[])	//判断一个字符串是否为回文串
{
    
    
	int j, i, n;
	char b[1000];
	n = strlen(a);
	for(i = 0, j = n - 1; i < n; i++, j--)
		b[j] = a[i];
	for(i = 0; i < n; i++)
		if(b[i] != a[i]) break;
	i == n ? printf("回文\n") : printf("不回文\n");
}

C language code:

#include<stdio.h>
#include<string.h>
int main()
{
    
    
    int n;
    char s[1024];
    char t[1024];
    scanf("%d%*c", &n);
    while(n--)
    {
    
    
        gets(s);
        strcpy(t, s);
        strrev(s);
        puts(strcmp(t, s) ? "no" : "yes");
    }
    return 0;
}

C++ code:

#include<bits/stdc++.h>
using namespace std;
char s[10005];
void Is_String_Palindrome(char a[])
{
    
    
	int j, i, n;
	char b[1005];
	n = strlen(a);
	for(i = 0, j = n - 1; i < n; i++, j--)
		b[j] = a[i];
	for(i = 0; i < n; i++)
		if(b[i] != a[i]) break;
	i == n ? printf("yes\n") : printf("no\n");
}
int main()
{
    
    
	int n;
	while(cin >> n)
	{
    
    
		for(int i = 0; i < n; i++)
		{
    
    
			cin >> s;
			Is_String_Palindrome(s);
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/113097884