python3整數反轉
給你一個 32 位的有符號整數 x ,回傳將 x 中的數字部分反轉后的結果,
如果反轉后整數超過 32 位的有符號整數的范圍 [?2^31, 2^31 ? 1] ,就回傳 0,
假設環境不允許存盤 64 位整數(有符號或無符號),
示例 1:
輸入:x = 123
輸出:321
示例 2:
輸入:x = -123
輸出:-321
示例 3:
輸入:x = 120
輸出:21
示例 4:
輸入:x = 0
輸出:0
思路1:將其轉為字串進行翻轉,并進行正負的判斷,最后,題目要求如果反轉后整數超過 32 位的有符號整數的范圍 [?2^31, 2^31 ? 1] ,就回傳 0
class Solution:
def reverse(self, x: int) -> int:
str1 = str(x)
if str1[0] == '-':
str1 = str1[0] + str1[:0:-1]
else:
str1 = str1[::-1]
return int(str1) if -2147483648<int(str1)<2147483648 else 0
思路2:不使用字串,當翻轉后的數字大于條件就回傳0
class Solution:
def reverse(self, x: int) -> int:
y, res = abs(x), 0
# 則其數值范圍為 [?2^31, 2^31 ? 1]
boundry = (1<<31) -1 if x>0 else 1<<31
while y != 0:
res = res*10 +y%10
if res > boundry :
return 0
y //=10
return res if x >0 else -res
改進:
class Solution:
def reverse(self, x: int) -> int:
str1 = str(x)
if str1[0] == '-':
str1 = str1[0] + str1[:0:-1]
a=int(str1)
if (1<<31)<abs(a):
return 0
else:
str1 = str1[::-1]
a= int(str1)
if a>(1<<31) -1:
return 0
return a
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/271226.html
標籤:AI
