[leetcode] 7. Reverse Integer @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86581365

原题

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.

解法

定义helper函数, 将非负数反转, 当x为负数时, 用helper(-x)*(-1)即可. 最后判断结果是否在区间内.

代码

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        def helper(x):
            return int(str(x)[::-1])
        
        if x >= 0:
            res = helper(x)
        else:
            res = (-1)*helper(-x)
            
        if res > 2**31-1 or res < -2**31:
            return 0
        return res

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/86581365