Palindrome Number Problem Solution

Palindrome Number Problem: Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward.

  • For example, 121 is a palindrome while 123 is not.

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Palindrome Number Problem Solution

Problem solution in Python

class Solution:
    def isPalindrome(self, x: int) -> bool:
        """ """
        temp = x
        reverse = 0
        while x > 0:
            reverse *= 10
            reverse += x % 10
            x //= 10
        return temp == reverse

Problem solution in Java

class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0)
            return false;
        else if(String.valueOf(x).length() == 1)
            return true;
        
        String str = String.valueOf(x);
        
        int i = 0;
        int j = str.length() -1;
        while(j > i){
            if(str.charAt(i) != str.charAt(j))
                return false;
            i++;
            j--;
        }
        return true;
    }
}

Problem solution in C++

class Solution {
public:
    bool isPalindrome(int x) {
            string s = to_string(x);
            int start = 0;
            int end = s.length() - 1;

            while(start < end)
            {
                if(s[start++] != s[end--])
                    return false;
            }

            return true;
        }
};

Problem solution in C

bool isPalindrome(int x) {
    if (x < 0) return false;
    long y=0;
    long xx=x;
    while (xx>0) {
        y = y*10 + xx%10;
        xx/=10;
    }
    return (y == x);
}


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment