Editorial
Algorithm Analysis
Read the input number as a string into a character array s
. Let len
be the length of the string s
, decreased by 1 (the index of the cell in the character array where the last digit of the number is located). The string is a palindrome if for all .
Consider the number 4570754 of length 7. Then len = 7 – 1 = 6
. The following equalities hold:
s[0] = s[6 - 0] = s[6] = ‘4’;
s[1] = s[6 - 1] = s[5] = ‘5’;
s[2] = s[6 - 2] = s[4] = ‘7’;
Algorithm Implementation
Read the input number into a character array s.
char s[50];
Read the input number as a string. Set len
equal to the index of the last digit.
gets(s); len = strlen(s) - 1; flag = 0;
Set flag = 0
, which means that the number is a palindrome. If the equality is violated for some i
, then the number is not a palindrome, set flag = 1
.
for(i = 0; i < len - i; i++) if (s[i] != s[len - i]) flag = 1;
Depending on the value of flag
, print the result.
if (flag == 0) printf("Yes\n"); else printf("No\n");
Implementation – Function IsPalindrome
#include <stdio.h> #include <string.h> char s[50]; int flag; int IsPalindrome(char *s) { int i = 0, j = strlen(s) - 1; while(i < j) { if (s[i] != s[j]) return 0; i++; j--; } return 1; } int main(void) { gets(s); flag = IsPalindrome(s); if (flag == 1) printf("Yes\n"); else printf("No\n"); return 0; }
Implementation – STL reverse
#include <cstdio> #include <iostream> #include <string> #include <algorithm> using namespace std; string p, q; int main(void) { cin >> p; q = p; reverse(q.begin(),q.end()); if (p == q) printf("Yes\n"); else printf("No\n"); return 0; }
Java Implementation
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); char[] s = con.nextLine().toCharArray(); int flag = 0, len = s.length - 1; for(int i = 0; i < len - i; i++) if (s[i] != s[len - i]) flag = 1; if (flag == 0) System.out.println("Yes"); else System.out.println("No"); con.close(); } }
Java Implementation – Function IsPalindrome
import java.util.*; public class Main { public static int IsPalindrome(String s) { int i = 0, j = s.length() - 1; while(i < j) { if (s.charAt(i) != s.charAt(j)) return 0; i++; j--; } return 1; } public static void main(String[] args) { Scanner con = new Scanner(System.in); String s = con.next(); int flag = IsPalindrome(s); if (flag == 1) System.out.println("Yes"); else System.out.println("No"); con.close(); } }
Python Implementation
a = input() if a == a[::-1]: print("Yes") else: print("No")