Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Basics

Palindrome Number

Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant

Print YES if the non-negative integer n reads the same forwards and backwards, otherwise NO.

Input

One integer n.

Output

YES or NO.

Constraints

Example 1

Input

121

Output

YES

Example 2

Input

123

Output

NO

Hints

  1. Reverse the number and compare it with the original.
  2. n goes up to 10^18 — reversing it can overflow 64 bits. Comparing digits as a string avoids that.

Approach

Read n as a string and compare it with its reverse, or use two pointers moving inward from both ends. Working with the string sidesteps overflow: the reverse of a 19-digit number like 9 000 000 000 000 000 001 doesn't fit in a signed 64-bit integer.

Complexity: O(number of digits) time · O(digits) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    int i = 0, j = (int)s.size() - 1;
    bool ok = true;
    while (i < j) {
        if (s[i++] != s[j--]) { ok = false; break; }
    }
    cout << (ok ? "YES" : "NO") << "\n";
    return 0;
}

Python solution

s = input().strip()
print("YES" if s == s[::-1] else "NO")

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        String rev = new StringBuilder(s).reverse().toString();
        System.out.println(s.equals(rev) ? "YES" : "NO");
    }
}

Solve Palindrome Number online · All practice problems