題目描述
將給出的整數(shù)x翻轉(zhuǎn)。
例1:x=123,返回321
例2:x=-123,返回-321
你有思考過下面的這些問題么?
如果整數(shù)的最后一位是0,那么輸出應(yīng)該是什么?比如10,100
你注意到翻轉(zhuǎn)后的整數(shù)可能溢出嗎?假設(shè)輸入是32位整數(shù),則將翻轉(zhuǎn)10000000003就會(huì)溢出,你該怎么處理這樣的樣例?拋出異常?這樣做很好,但是如果不允許拋出異常呢?這樣的話你必須重新設(shè)計(jì)函數(shù)(比如添加一個(gè)額外的參數(shù))。
示例1
輸入
-123
返回值
-321
解題思路:利用切片反轉(zhuǎn)技術(shù)
#
# @param x int整型
# @return int整型
#
class Solution:
? ? def reverse(self , x ):
? ? ? ? # write code here
? ? ? ? flag = False
? ? ? ? if x < 0:
? ? ? ? ? ? flag = True
? ? ? ? ? ? x = x*-1
? ? ? ? x = str(x)[::-1]
? ? ? ? x = -1 * int(x) if flag else int(x)
? ? ? ? return x
原文鏈接:金烏智能 -反轉(zhuǎn)數(shù)字?轉(zhuǎn)載請(qǐng)聯(lián)系:金烏智能--數(shù)據(jù)抓取、數(shù)據(jù)采集、爬蟲