The Wayback Machine - https://web.archive.org/web/20241119062540/https://www.geeksforgeeks.org/check-if-a-number-is-palindrome/
Open In App

Check if a number is Palindrome

Last Updated : 19 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a positive integer N, find whether the number is Palindrome or not. A number is Palindrome if it remains the same when its digits are reversed.

Examples:

Input: N = 12321
Output: Yes
Explanation: 12321 is a Palindrome number because after reversing its digits, the number becomes 12321 which is same as the original number.

Input: N = 1234
Output: No
Explanation: 1234 is not a Palindrome number because after reversing its digits, the number becomes 4321 which is different from the original number.

[Expected Approach] Comparing with reverse of original number – O(Number of digits) Time and O(1) Space:

The idea is to find the reverse of the original number and then compare the reversed number with the original number. If the reversed number is same as the original number, the number is Palindrome. Otherwise, the number is not a Palindrome.

Below is the implementation of the above algorithm:

C++
// C++ program to check if a number is Palindrome
#include <iostream>
using namespace std;
// Function to check Palindrome
bool checkPalindrome(int n)
{
    int reverse = 0;
    // Copy of the original number so that the original
    // number remains unchanged while finding the reverse
    int temp = n;
    while (temp != 0) {
        reverse = (reverse * 10) + (temp % 10);
        temp = temp / 10;
    }
    // If reverse is equal to the original number, the
    // number is palindrome
    return (reverse == n);
}
int main()
{
    // Sample Input
    int n = 12321;
    if (checkPalindrome(n) == 1) {
        cout << "Yes\n";
    }
    else {
        cout << "No\n";
    }
    return 0;
}
Java
// Java Program to check if a number is Palindrome 
public class GFG {
    // Function to check Palindrome
    public static boolean checkPalindrome(int n)
    {
        int reverse = 0;
        // Copy of the original number so that the original
        // number remains unchanged while finding the
        // reverse
        int temp = n;
        while (temp != 0) {
            reverse = (reverse * 10) + (temp % 10);
            temp = temp / 10;
        }
        // If reverse is equal to the original number, the
        // number is palindrome
        return (reverse == n);
    }

    // Main method (equivalent of Driver code)
    public static void main(String[] args)
    {
        // Sample Input
        int n = 12321;
        if (checkPalindrome(n)) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
}
Python
# Python3 program to check if a number is Palindrome

# Function to check Palindrome
def check_palindrome(n):
    reverse = 0
    # Copy of the original number so that the original
    # number remains unchanged while finding the reverse
    temp = n
    while temp != 0:
        reverse = reverse * 10 + temp % 10
        temp = temp // 10
    # If reverse is equal to the original number, the
    # number is palindrome
    return reverse == n

# Sample Input
n = 12321
if check_palindrome(n):
      print("Yes")
else:
      print("No")
C#
// C# program to check if a number is Palindrome

using System;

public class GFG
{
    // Function to check Palindrome
    public static bool CheckPalindrome(int n)
    {
        int reverse = 0;
        // Copy of the original number so that the original
        // number remains unchanged while finding the reverse
        int temp = n;
        while (temp != 0)
        {
            reverse = (reverse * 10) + (temp % 10);
            temp = temp / 10;
        }
        // If reverse is equal to the original number, the
        // number is palindrome
        return (reverse == n);
    }

    // Main method
    public static void Main()
    {
        // Sample Input
        int n = 12321;
        if (CheckPalindrome(n))
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
}
JavaScript
// Javascript Program to check if a number is palindrome

// Function to check Palindrome
function checkPalindrome(n) {
    let reverse = 0;
    // Copy of the original number so that the original
    // number remains unchanged while finding the reverse
    let temp = n;
    while (temp !== 0) {
        reverse = (reverse * 10) + (temp % 10);
        temp = Math.floor(temp / 10);
    }
    // If reverse is equal to the original number, the
    // number is palindrome
    return reverse === n;
}


// Sample Input
let n = 12321;
if (checkPalindrome(n)) {
console.log("Yes");
} else {
console.log("No");
}

Output
Yes

Time Complexity : O(log10(N)) or O(Number of digits in a given number)
Auxiliary space : O(1) or constant

[Other Approach] Using Number as String – O(Number of digits) Time and O(1) Space:

When the input number exceeds 1018, then finding the reverse can cause overflow in languages like: C, C++, Java, etc. So, we can take the input number as a string and run a loop from starting to length/2 and compare the first character(numeric) with the last character of the string, second character to second last one, and so on. If any character mismatches, the string wouldn’t be a palindrome.

Below is the implementation of the above approach

C++14
// C++ implementation of the above approach
#include <iostream>
using namespace std;

// Function to check palindrome
int checkPalindrome(string str)
{
    // Calculating string length
    int len = str.length();

    // Traversing through the string
    // upto half its length
    for (int i = 0; i < len / 2; i++) {

        // Comparing i th character
        // from starting and len-i
        // th character from end
        if (str[i] != str[len - i - 1])
            return false;
    }

    // If the above loop doesn't return then it is
    // palindrome
    return true;
}

// Driver Code
int main()
{ // taking number as string
    string st
        = "112233445566778899000000998877665544332211";
    if (checkPalindrome(st) == true)
        cout << "Yes";
    else
        cout << "No";
    return 0;
}
Java
// Java implementation of the above approach
import java.io.*;

class GFG {

    // Function to check palindrome
    static boolean checkPalindrome(String str)
    {

        // Calculating string length
        int len = str.length();

        // Traversing through the string
        // upto half its length
        for (int i = 0; i < len / 2; i++) {

            // Comparing i th character
            // from starting and len-i
            // th character from end
            if (str.charAt(i) != str.charAt(len - i - 1))
                return false;
        }

        // If the above loop doesn't return then
        // it is palindrome
        return true;
    }

    // Driver Code
    public static void main(String[] args)
    {

        // Taking number as string
        String st
            = "112233445566778899000000998877665544332211";

        if (checkPalindrome(st) == true)
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}
Python
# Python3 implementation of the above approach

# function to check palindrome
def checkPalindrome(str):
  
    # Run loop from 0 to len/2
    for i in range(0, len(str)//2):
        if str[i] != str[len(str)-i-1]:
            return False
          
    # If the above loop doesn't 
    #return then it is palindrome
    return True


# Driver code
st = "112233445566778899000000998877665544332211"
if(checkPalindrome(st) == True):
    print("Yes")
else:
    print("No")
C#
// C# implementation of the above approach
using System;

class GFG {

    // Function to check palindrome
    static bool checkPalindrome(string str)
    {

        // Calculating string length
        int len = str.Length;

        // Traversing through the string
        // upto half its length
        for (int i = 0; i < len / 2; i++) {

            // Comparing i th character
            // from starting and len-i
            // th character from end
            if (str[i] != str[len - i - 1])
                return false;
        }

        // If the above loop doesn't return then
        // it is palindrome
        return true;
    }

    // Driver Code
    public static void Main()
    {

        // Taking number as string
        string st
            = "112233445566778899000000998877665544332211";

        if (checkPalindrome(st) == true)
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
JavaScript
// Javascript implementation of the above approach

// Function to check palindrome
function checkPalindrome(str)
{ 
    // Calculating string length
    var len = str.length;
   
    // Traversing through the string 
    // upto half its length
    for (var i = 0; i < len / 2; i++) {
       
        // Comparing ith character 
        // from starting and len-ith
        // character from end
        if (str[i] != str[len - i - 1])
            return false;
    }
   
    // If the above loop doesn't return then it is
    // palindrome
    return true;
}
 
// Driver Code
// taking number as string
let st = "112233445566778899000000998877665544332211";
if (checkPalindrome(st) == true)
    console.log("Yes");
else
    console.log("No");

Output
Yes

Time Complexity: O(|str|) or O(number of digits)
Auxiliary Space: O(1)  



Previous Article
Next Article

Similar Reads

Count all palindrome which is square of a palindrome
Given two positive integers L and R (represented as strings) where [Tex]1\leq L \leq R\leq10^{18} [/Tex]. The task is to find the total number of super-palindromes in the inclusive range [L, R]. A palindrome is called super-palindrome if it is a palindrome and also square of a palindrome. Examples: Input: L = "4", R = "1000" Output: 4 Explanation:
10 min read
Check if a number with even number of digits is palindrome or not
Given a number N containing an even number of digits. The task is to check whether that number is palindrome or not. Examples: Input: N = 123321 Output: Palindrome Input: 1234 Output: Not palindrome A Naive Approach is to traverse from the front and back of that number and stop where they do not match.An Efficient Approach is to use the below fact:
4 min read
Bash program to check if the Number is a Palindrome
Given a number num, find whether the given number is palindrome or not using Bash Scripting. Examples: Input : 666 Output : Number is palindrome Input : 45667 Output : Number is NOT palindrome Approach To find the given number is palindrome just check if the number is same from beginning and the end. Reverse the number to check if the number revers
1 min read
Check if a number is Palindrome in PL/SQL
Given an integer, write a function that returns true if the given number is palindrome, else false. For example, 12321 is palindrome, but 1451 is not palindrome. Let the given number be num. A simple method for this problem is to first reverse digits of num, then compare the reverse of num with num. If both are same, then return true, else false. E
1 min read
Check if Nodes in Top view of a Binary Tree forms a Palindrome Number or not
Given a binary tree consisting of N nodes, the task is to check if the nodes in the top view of a Binary Tree forms a palindrome number or not. If found to be a palindrome, then print "Yes". Otherwise, print "No". Examples: Input: 5 / \ 3 3 / \ \ 6 2 6Output: YesExplanation:Nodes in the top view are {6, 3, 5, 3, 6}. Hence, the generated number ( =
10 min read
Check whether the given floating point number is a palindrome
Given a floating-point number N, the task is to check whether it is palindrome or not. Input: N = 123.321 Output: YesInput: N = 122.1 Output: No Approach: First, convert the given floating-point number into a character array.Initialize the low to first index and high to the last index.While low < high: If the character at low is not equal to the
4 min read
Check if string remains palindrome after removing given number of characters
Given a palindromic string str and an integer N. The task is to find if it is possible to remove exactly N characters from the given string such that the string remains a palindrome. Examples: Input: str = "abba", N = 1 Output: Yes Remove 'b' and the remaining string "aba" is still a palindrome. Input: str = "aba", N = 1 Output: Yes Approach: It ca
3 min read
Check if number is palindrome or not in base B
Given an integer N, the task is to check if [Tex]N_B [/Tex] (N in base B) is palindrome or not. Examples: Input: N = 5, B = 2 Output: Yes Explanation: (5)10 = (101)2 which is palindrome. Therefore, the required output is Yes.Input: N = 4, B = 2 Output: No Approach: The problem can be solved by checking if the decimal value of the reverse of [Tex]N_
4 min read
Check if a number is palindrome or not without using any extra space | Set 2
Given a number ‘n’ and our goal is to find out it is palindrome or not without using any extra space. We can’t make a new copy of number. Examples: Input: n = 2332Output: Yes it is Palindrome.Explanation:original number = 2332reversed number = 2332Both are same hence the number is palindrome. Input: n=1111Output: Yes it is Palindrome. Input: n = 12
5 min read
Check if actual binary representation of a number is palindrome
Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0’s are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Input : 10 Output : No (10)10 = (1010)2Recommended Pr
6 min read
Program to check the number is Palindrome or not
Given an integer N, write a program that returns true if the given number is a palindrome, else return false. Examples: Input: N = 2002 Output: trueInput: N = 1234Output: false Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. Approach: A simple method for this problem is to first reverse digits of n, then compare
10 min read
Generate number with given operation and check if it is palindrome
Given an integer N the task is to create a string out of it by repeating the number such that the length of the resultant string is equal to the sum of the digits in the original number. For eg: If the number is 61 and the sum of the digits is 6 + 1 = 7 so the string generated after repeating 61 will be of 7 length i.e. 6161616. Examples: Input: N
7 min read
Check if binary representation of a number is palindrome
Given an integer 'x', write a C function that returns true if binary representation of x is palindrome else return false.For example a numbers with binary representation as 10..01 is palindrome and number with binary representation as 10..00 is not palindrome.The idea is similar to checking a string is palindrome or not. We start from leftmost and
15 min read
To check a number is palindrome or not without using any extra space
Given a number 'n' and our goal is to find out it is palindrome or not without using any extra space. We can't make a new copy of the number . Examples: Input : 2332 Output : Yes it is Palindrome. Explanation: original number = 2332 reversed number = 2332 Both are same hence the number is palindrome. Input :1111 Output :Yes it is Palindrome. Input
6 min read
Check if number is palindrome or not in Octal
Given a number which may be in octal or in decimal. If the number is not octal then convert it into octal then check if it is palindrome or not. If it is palindrome then print 1 otherwise print 0. If the number is already in octal then check if the number is palindrome or not.Examples : Input :n = 111 Output : Yes Explanation: all digits of 111 are
7 min read
Smallest number to be subtracted to convert given number to a palindrome
Given an integer N, the task is to find the smallest number to be subtracted from N to obtain a palindrome. Examples: Input: N = 1000Output: 1Explanation: Since 1000 – 1 = 999, which is a palindrome, the smallest number to be subtracted is 1. Input: N = 3456Output: 13Explanation: Since 3456 – 13 = 3443, which is a palindrome, the smallest number to
5 min read
Reverse and Add given number repeatedly to get a Palindrome number
Write a program that takes number and gives the resulting palindrome (if one exists). If it took more than 1, 000 iterations (additions) or yield a palindrome that is greater than 4, 294, 967, 295, assume that no palindrome exist for the given number. Examples: Input: N = 195 Output: 9339 Input: N = 265 Output: 45254 Input: N = 196 Output: No palin
6 min read
Check if given Binary String can be made Palindrome using K flips
Given a binary string str, the task is to determine if string str can be converted into a palindrome in K moves. In one move any one bit can be flipped i.e. 0 to 1 or 1 to 0. Examples: Input: str = "101100", K = 1Output: YESExplanation: Flip last bit of str from 0 to 1. Input: str = "0101101", K = 2Output: NOExplanation: Three moves required to mak
5 min read
Program to check if an array is palindrome or not using Recursion
Given an array. The task is to determine whether an array is a palindrome or not using recursion. Examples: Input: arr[] = {3, 6, 0, 6, 3}Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5}Output: Not Palindrome Approach: Base case: If array has only one element i.e. begin == end then return 1, also if begin>end which means the array is palindrome
4 min read
Check if a string can be rearranged to form special palindrome
Given a string str, the task is to check if it can be rearranged to get a special palindromic string. If we can make it print YES else print NO. A string is called special Palindrome that contains an uppercase and a lower case character of the same character in the palindrome position. Example: ABCcba is a special palindrome but ABCCBA is not a spe
8 min read
Check if there exists any sub-sequence in a string which is not palindrome
Given a string of lowercase English alphabets. The task is to check if there exists any subsequence in the string which is not a palindrome. If there is at least 1 subsequence that is not a palindrome then print YES, otherwise print NO. Examples: Input : str = "abaab"Output: YESSubsequences "ab" or "abaa" or "aab", are not a palindrome.Input : str
8 min read
Program to check if an Array is Palindrome or not
Given an array, the task is to determine whether an array is a palindrome or not.Examples: Input: arr[] = {3, 6, 0, 6, 3} Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5} Output: Not Palindrome Approach: Initialise flag to unset int flag = 0.Loop the array till size n/2In a loop check if arr[i]! = arr[n-i-1] then set the flag = 1 and breakAfter th
5 min read
Queries to check if substring[L...R] is palindrome or not
Given a string str and Q queries. Every query consists of two numbers L and R. The task is to print if the sub-string[L...R] is palindrome or not. Examples: Input: str = "abacccde", Q[][] = {{0, 2}, {1, 2}, {2, 4}, {3, 5}} Output: Yes No No Yes Input: str = "abaaab", Q[][] = {{0, 1}, {1, 5}} Output: No Yes Recommended: Please try your approach on {
13 min read
Check if string can be rearranged so that every Odd length Substring is Palindrome
Given a string S. The task is to check whether it is possible to rearrange the string such that every substring of odd length is a palindrome. Examples: Input: S = "oiooi" Output: YES The string can be rearranged as "oioio" Input: S = "yuyuo" Output: NO Approach: The very first observation is if all the characters of the string are the same then ev
7 min read
Check if String formed by first and last X characters of a String is a Palindrome
Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false. Examples: Input: str = abcdefba, X = 2Output: trueExplanation: First 2 characters of both string str and reversed string str are same. Input: str =
5 min read
Check if the sum of digits of N is palindrome
Given an integer N, the task is to check whether the sum of digits of N is palindrome or not.Example: Input: N = 56 Output: Yes Explanation: Digit sum is (5 + 6) = 11, which is a palindrome. Input: N = 51241 Output: No Approach: Find the sum of digits of N and store it in a variable sum. Now check whether sum is palindrome or not using the approach
9 min read
Queries to check if the path between two nodes in a tree is a palindrome
Given a tree with N nodes and N - 1 edges. Each edge of the tree is labeled by a string of lowercase english alphabets. You are given Q queries. In each query you are given two node x and y. For the path between x to y, the task is to check if it is possible to make a new palindrome string which use all the characters in the path from node x to nod
15+ min read
Check if sum of any subarray is Palindrome or not
Given an array arr[] of size N. the task is to check whether there exists any subarray of size atleast 2 such that its sum is palindrome. If such a subarray exists, then print YES. Otherwise, print NO.Examples: Input: arr[] = {10, 6, 7, 9, 12} Output: Yes Explanation: The subarray [6, 7, 9] with sum 22 is palindrome.Input: arr[] = {15, 4, 8, 2} Out
8 min read
Check if longest connected component forms a palindrome in undirected graph
Given an undirected graph with V vertices and E edges, the task is to check that if the largest connected component of the graph forms a palindrome in the undirected graph. Examples: Input: Output: Longest connected component is Palindrome Explanation: Longest connected component is {5, 15, 5} which forms an palindrome by values. Input: Output: Lon
15+ min read
Check if string is palindrome after removing all consecutive duplicates
Given a string str, the task is to remove all the consecutive duplicates from the string str and check if the final string is palindrome or not. Print "Yes" if it is a palindromic else print "No". Examples: Input: str = "abbcbbbaaa" Output: Yes Explanation: On removing all consecutive duplicates characters, the string becomes "abcba" which is a pal
7 min read
three90RightbarBannerImg