1. 程式人生 > >【LeetCode每天一題】Reverse Integer(反轉數字)

【LeetCode每天一題】Reverse Integer(反轉數字)

ever 標誌位 leet log out with pan returns NPU

Given a 32-bit signed integer, reverse digits of an integer.

Example 1: Input: 123 Output: 321

Example 2: Input: -123 Output: -321

Example 3: Input: 120 Output: 21

Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

思路:對於負數設置一個標誌位,然後將其轉化成正整數,再來計算,最後判斷大小是否超過了[−231

, 231 − 1]這個範圍。時間復雜度為O(log 10 x), 空間復雜度為O(1)。

代碼


 1 class Solution(object):
 2     def reverse(self, x):
 3         """
 4         :type x: int
 5         :rtype: int
 6         """
 7         if x == 0:                     # 為0直接返回
 8             return 0
 9         res, neg_flag = 0
,False # 設置結果和負數標誌位 10 if x < 0: 11 neg_flag = True 12 x = abs(x) 13 while x: # 進行反轉 14 tem = x % 10 15 x = x// 10 16 res = (res*10 + tem) 17 if neg_flag: # 判斷舒服標誌位,並進行相應的轉換 18 res = 0-res 19 if res > pow(2,31)-1 or res < -pow(2,31): # 判斷是否超出範圍, 直接返回0 20 return 0 21 return res # 返回結果

【LeetCode每天一題】Reverse Integer(反轉數字)