Palindrome Number | LeetCode 9 | Python | Solution

LeetCode 9

Before getting into the solution, let’s see the definition of a palindrome. According to Wikipedia:

A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward

So to solve this problem, we have to reverse the given number. After that, we can check both versions are the same or not.

One easy way to reverse a number is to convert it into a string, then use the built-in reverse function. After that, we can check the original one with the reversed one. And based on that, we can return True or False.

class Solution:
    def isPalindrome(self, x: int) -> bool:
        s = str(x)
        return s == s[::-1]

But there is another good solution. We can reverse a number using a simple math formula. Let’s see that one.

class Solution:
    def isPalindrome(self, x: int) -> bool:
        return x == self.reverse_number(x)
    def reverse_number(self, x):
        num = 0
        while x > 0:
            # The following formula will continue until the given number has become zero. 
            reminder = x % 10
            num = num * 10 + reminder
            x = x // 10
        return num

Happy Learning.
Happy Coding.