Palindrome Number in Python

PythonServer Side ProgrammingProgramming

Suppose we have integer. We have to check whether the integer is palindrome or not. So is the integer is same in forward or reverse order both, then the number is palindrome. For an example suppose the number is 454, if we reverse it will be 454 again. So this is palindrome. Now if the number is -565, then the reverse will be 565-, that is not same, so this will not be palindrome.

To solve this, we will convert the number as string, then reverse the string. If the string and reversed string are same, then the number is palindrome. So return true in that case, otherwise return false.

Let us see the implementation to get better understanding

Example

Live Demo

class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
val = str(x)
return val == val[::-1]
ob1 = Solution()
print(ob1.isPalindrome(424))
print(ob1.isPalindrome(-565))

Input

x = 424
x = -565

Output

True
False
Published on 08-Jan-2020 10:32:50