【每日一题Leetcode】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(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        # check sign of integer and change to positive number
        sign = 1 if x > 0 else -1
        x = x * sign

        # check digit
        if x < 10:
            return x*sign
        
        rev = 0        
        while True:
            # check if overflow
            if (rev >= 2**31-1) or (rev <= -2**31):
                return 0
            # get div and remainder
            x,rem = divmod(x,10)   
            if rem != 0:
                rev = rev*10+rem*10
            else:
                rev = rev*10
                    
            if x < 10:
                rev += x
                break 
        # double check if overflow        
        rev = rev * sign if rev<=2**31-1 else 0
        return rev
                

看到这个题有另一种解题思路,将x转换成字符再反转, 比如str(x)[::-1]

猜你喜欢

转载自blog.csdn.net/github_39395521/article/details/81096026