Reverse Integer|數字反轉
LeetCode 7. Reverse Integer 的解題筆記,用字串反轉處理整數,並在不使用 64 位元整數的前提下檢查邊界。
更新於 2026年7月30日
原題:LeetCode 7. Reverse Integer
難度:Medium
主題:Math
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
給定一個整數,將其進行反轉後輸出。必須注意環境中不允許使用64位元整數。
Example 1:
Input: x = 123
Output: 321Example 2:
Input: x = -123
Output: -321Example 3:
Input: x = 120
Output: 21Constraints:
- -2^31 <= x <= 2^31 - 1
Solution
反轉字串
思路:將整數轉換成字串,反轉後再轉回整數輸出。
同樣要在不用 64 位元整數的前提下處理 32 位元邊界的還有「String to Integer (atoi)|字串轉整數」,那題的要求是夾進範圍內而不是回 0。
複雜度:O(n)
class Solution:
def reverse(self, x):
res = int(str(x)[::-1]) if x >= 0 else -1 * int(str(-x)[::-1])
return res if res < 2**31 and res >= -2**31 else 0結果:24ms, beats 99.42% of users with Python3.