DEV Community

睡觉
睡觉

Posted on • Edited on

Five simple ways to tackle Palindrome Number (Easy) | LeetCodePractice #2

Palindrome Number (LeetCode 9)

Given an integer x, return true if x is a palindrome, and false otherwise.

Python

####Two Pointer (Runtime: 10ms, Memory: 12.4MB)
    #DECLARE x: INTEGER
class Solution:
    def isPalindrome(self, x):
        y = str(x)
        head = 0
        tail = len(y) - 1
        while head < tail:
            if y[head] != y[tail]:
                return False
            head += 1
            tail -= 1
        return True



####Recursion (Runtime: 12ms, Memory: 12.3MB)
    #DECLARE x: INTEGER
class Solution:
    def isPalindrome(self, x):
        y = str(x)
        if y[0] != y[-1]:
            return False
        if len(y) <= 2:
            return True
        return self.isPalindrome(y[1:-1])



####Slicing with Radius Check (Runtime: 0ms, Memory: 12.3MB)
    #DECLARE x: INTEGER
class Solution:
    def isPalindrome(self, x):
        y = str(x)
        radius = len(y) // 2
        return y[:radius] == y[::-1][:radius]



####Mathematical Calculation (Runtime: 16ms, Memory: 12.4MB)
    #DECLARE x: INTEGER
class Solution:
    def isPalindrome(self, x):
        if x < 0:
            return False
        reverse_num = 0
        y = x
        while y > 0:
            reverse_num = reverse_num * 10 + (y%10)
            y = y // 10
        return x == reverse_num



####Calculation and Half Reverse (Runtime: 3ms, Memory: 12.3MB)
    #DECLARE x: INTEGER
class Solution:
    def isPalindrome(self, x):
        if x < 0 or (x%10==0 and x!=0):
            return False
        y = x
        reverse_num = 0
        while y > reverse_num:
            reverse_num = reverse_num * 10 + (y%10)
            y = y // 10
        if y == reverse_num or y == (reverse_num//10):
            return True
        return False
Enter fullscreen mode Exit fullscreen mode

Thoughts

Well, the last one definitely gave me a headache. I'm not really sensitive to numbers, and failing to consider that "zeros can't be at the front" didn't help either. So, there's a lesson for me: get rid of difficult cases at the start so that you don't need to make more adjustments afterward.

Top comments (0)