【Leetcode】python - [7] Reverse Integer 個人解法筆記

題目出處

7. Reverse Integer

難度

medium

個人範例程式碼

class Solution:
    def reverse(self, x: int) -> int:

        negative_flag = False
        if x < 0:
            x = -x
            negative_flag = True

        ans = int(str(x)[::-1])
        if ans >= (1 << 31) -1:
            return 0
        return -ans if negative_flag else ans

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

算法說明

先抽出負號,再直接以 string 的方式顛倒,
需要注意題目要求數值範圍介於 -2^31 ~ 2^31-1 之間,
2^31 = (1 « 31)

input handling

處理負號,拿出來後再丟回去。

Boundary conditions

處理好數字範圍

Reference