LeetCode 筆記 - 7. Reverse Integer Posted on 2022-05-09 LeetCode 第 7 題解析,要求將一個 32 位元的有號整數進行反轉。本文分享如何透過基礎的數學運算處理位元反轉,並特別提醒開發者注意反轉後可能產生的數值溢位(Overflow)問題,確保結果符合 32 位元整數的範圍限制。題目在此 7. Reverse Integer將數字反轉解題思維給定一個數字,將數字反轉。Time complexity: O(1)程式碼123456789101112131415161718192021class Solution: def reverse(self, x: int) -> int: x = str(x) if len(x) < 2: return x if x.startswith('-'): x = x[::-1] x = f'-{x[:-1]}' else: x = x[::-1] x = int(x) # overflow if x >= 2147483651: return 0 if x <= -2147483651: return 0 return x也許你也會想看看LeetCode 筆記 - 9. Palindrome NumberLeetCode 筆記 - 344. Reverse StringLeetCode 筆記 - 733. Flood Fill