iT邦幫忙

第 11 屆 iThome 鐵人賽

1
Software Development

LeetCode刷題日記系列 第 23

【Day 23】#9 - Palindrome Number

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

Example 1:

Input: 121
Output: true

Example 2:

Input: -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: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:
Coud you solve it without converting the integer to a string?

解析

此題要求判斷數值是否為左右對稱。可透過比對原數值與反轉後的數值是否相等來解。
若要完成Follow up條件,可透過比對其中一半數字是否跟另一半數字對稱來達成。

解法

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

Follow up

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0 or x % 10 == 0 and x != 0:
            return False

        revertedNumber = 0;
        while x > revertedNumber:
            revertedNumber = revertedNumber * 10 + x % 10;
            x //= 10;

        # When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
        # For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
        # since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
        return x == revertedNumber or x == revertedNumber//10

備註


希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。


上一篇
【Day 22】#2 - Add Two Numbers
下一篇
【Day 24】#1260 - Shift 2D Grid
系列文
LeetCode刷題日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言