[leetcode]7. Reverse Integer

注意翻转后不要超限:

Submission Detail

1032 / 1032 test cases passed.
Status: 

Accepted

Runtime: 40 ms
Memory Usage: 13.2 MB
Submitted: 0 minutes ago

Accepted Solutions Runtime Distribution

class Solution:
    def reverse(self, x: int) -> int:
        #define maxnum 2^32
        maxnum = 0x80000000
        if (x < -maxnum) or (x > (maxnum-1)) or x == 0:
            return 0
        
        #normal
        if (x<0):
            #min
            x = str(-x)
            x = x[::-1]
            x = int(x)  #deal pre-0
            if x < maxnum:      #returns 0 when the reversed integer overflows.
                return -x
            else:
                return 0
            
        else:
            #plus
            x = str(x)
            x = x[::-1]
            x = int(x)
            if x < maxnum-1:
                return x
            else:
                return 0
原文地址:https://www.cnblogs.com/alfredsun/p/10797643.html