成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python3整數(shù)反轉(zhuǎn)的實(shí)現(xiàn)方法

瀏覽:121日期:2022-06-23 15:47:24

給你一個(gè) 32 位的有符號(hào)整數(shù) x ,返回將 x 中的數(shù)字部分反轉(zhuǎn)后的結(jié)果。

如果反轉(zhuǎn)后整數(shù)超過(guò) 32 位的有符號(hào)整數(shù)的范圍 [−2^31, 2^31 − 1] ,就返回 0。

假設(shè)環(huán)境不允許存儲(chǔ) 64 位整數(shù)(有符號(hào)或無(wú)符號(hào))。

示例 1:

輸入:x = 123輸出:321

示例 2:

輸入:x = -123輸出:-321

示例 3:

輸入:x = 120輸出:21

示例 4:

輸入:x = 0輸出:0

思路1:將其轉(zhuǎn)為字符串進(jìn)行翻轉(zhuǎn),并進(jìn)行正負(fù)的判斷。最后,題目要求如果反轉(zhuǎn)后整數(shù)超過(guò) 32 位的有符號(hào)整數(shù)的范圍 [−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:不使用字符串。當(dāng)翻轉(zhuǎn)后的數(shù)字大于條件就返回0

class Solution: def reverse(self, x: int) -> int: y, res = abs(x), 0 # 則其數(shù)值范圍為 [−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

改進(jìn):

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 補(bǔ)充:?jiǎn)枺赫f(shuō)說(shuō)Python反轉(zhuǎn)三位整數(shù)有幾種方法?

答:這是leetcode上的一道編程算法題,感覺(jué)還是蠻經(jīng)典的,今天就拿出來(lái)給大家分享一下!給出一個(gè)3位的正整數(shù),你需要將這個(gè)整數(shù)中每位上的數(shù)字進(jìn)行反轉(zhuǎn)。例如:輸入: 123,輸出: 321 。大家先不看下面答案,看看如果是自己,可以想出幾種Python方式來(lái)解決!

下面分別來(lái)說(shuō)說(shuō)幾種實(shí)現(xiàn)的方式:

1、取余取整方式

class Test: def reverseInteger(self, number): g = number%10 #取出個(gè)位數(shù) s = (int(number/10))%10 #取出十位數(shù) b = int(number/100) #取出百位數(shù) return g*100+s*10+bif __name__ == '__main__': ts = Test() print (ts.reverseInteger(123)) #輸出結(jié)果:321

2、使用棧的方式

class Test: def reverseInteger(self, number): number = str(number) # 模擬入棧 l = list(number) result = '' while len(l) > 0: result += l.pop() # 模擬出棧 return int(result)if __name__ == '__main__': ts = Test() print (ts.reverseInteger(123)) # 輸出結(jié)果:321

3、使用切片的方式

class Test: def reverseInteger(self, number): number=str(number) result=number[::-1] #python中切片的特殊用法 result=(int(result)) return resultif __name__ == '__main__': ts = Test() print (ts.reverseInteger(123))

4、整數(shù)轉(zhuǎn)字符串,反轉(zhuǎn)字符串,然后再轉(zhuǎn)整數(shù)

class Test: def reverseInteger(self, x): plus_minus = '' reverse_x = '' if x < 0: plus_minus = '-' x = -x for i in str(x): reverse_x = i + reverse_x reverse_x = plus_minus + reverse_x if int(reverse_x) > pow(2, 31) - 1 or int(reverse_x) < pow(-2, 31): return 0 return int(reverse_x) if __name__ == '__main__': ts = Test() print (ts.reverseInteger(123)) #輸出結(jié)果:321

到此這篇關(guān)于python3整數(shù)反轉(zhuǎn)的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)python3 整數(shù)反轉(zhuǎn)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章: