iT邦幫忙

2022 iThome 鐵人賽

DAY 21
0
自我挑戰組

LeetCode Top 100 Liked系列 第 21

[Day 21] Palindrome Number (Easy)

  • 分享至 

  • xImage
  •  

9. Palindrome Number

Question

Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.

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.

Solution 1: Convert to String + Reverse

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

Time Complexity: O(N)
Space Complexity: O(N)

Solution 2: Reverse Int + Compare Int

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        revX = 0
        oriX = x
        while oriX:
            revX = (10*revX) + (oriX % 10)
            oriX //= 10
        return revX == x

Time Complexity: O(N)
Space Complexity: O(1)

Solution 3: Compare Head & Tail Digit

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        headDivisor = 1
        while x // headDivisor >= 10:
            headDivisor *= 10
        while headDivisor >= 10:
            # Cmp head & tail digit
            if (x // headDivisor) != (x % 10):
                return False
            # Moving Head & Tail Digit to Center
            x = (x % headDivisor) // 10
            headDivisor //= 100
        return True

Time Complexity: O(N)
Space Complexity: O(1)

Reference

https://medium.com/@oange6214/leetcode-%E6%88%91%E5%9C%A8%E5%A4%B1%E6%95%97%E7%9A%84%E8%B7%AF%E4%B8%8A-part-4-9-palindrome-number-3a45ce5ee6b3

Follow-up: Strictly Palindromic Number


上一篇
[Day 20] House Robber (Medium)
下一篇
[Day 22] LRU Cache (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言