# Leetcode 7. Reverse Integer ## 題解 ### 數學 #### 利用 Array 儲存 ```python! class Solution: def reverse(self, x: int) -> int: # Time complexity: O(n) # Space complexity: O(n) nums = [] isn = -10 if x < 0 else 10 while x != 0: nums.append(x % isn) x //= isn if isn == -10: x = -x output = 0 while len(nums) > 0: num = nums.pop(0) n = len(nums) output += num * (10 ** n) return output if (-2 ** 31) <= output <= (2 ** 31) -1 else 0 # 記得最後要判斷是否有在範圍內 ``` #### 取 log10 ```python! import math class Solution: def reverse(self, x: int) -> int: # Time complexity: O(n) # Space complexity: O(1) if x == 0: return x original_x = x x = x if x >= 0 else x * -1 digits = int(math.log10(x)) + 1 ans = 0 while digits: ans += ((x % 10) * (10 ** (digits - 1))) x //= 10 digits -= 1 ans *= -1 if original_x < 0 else 1 return ans if -2 ** 31 <= ans <= (2 ** 31) - 1 else 0 ```