[Math]007 Reverse Integer

  • 分類:Math

  • 考察知識點:Math

  • 最優(yōu)解時間復雜度:**O(n) **

7.Reverse Integer

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.

代碼:

我的方法:

class Solution:
    def reverse(self, x):
        if x<-2**31 or x>2**31-1 or x==0:
            return 0
        
        res=0
        s=1
        if x<0:
            s=-1
            x=-x
            
        while x:
            res=(res+(x%10))*10
            print(res)
            x=x//10
            
        res=res//10*s
        if res<-2**31 or res>2**31-1:
            return 0
        return res

討論:

1.簡單哦

Perfect
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容