LeetCode_Python3: 7. 反转整数(简单)

开始之前:从2018/8/27开始刷LeetCode,计划每周刷五题,周末进行总结并发布在csdn上,计划先刷150道题,从简单开始。

week 1-2


要求:

CODE:

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        
        # 不包含负号时,转换为字符串反转再装回int
        # 负数时,先去了符号,反转后再加上即可
        x = int(str(x)[::-1]) if x>= 0 else -int(str(-x)[::-1]) 
        
        # 判断是否存在溢出现象,如果溢出返回0否则x
        return 0 if x < -2**31 or x > 2**31-1 else x

结果:

知识点:

1. str[::-1]代表反转字符串

2. int32的范围为[-2^31, 2^31-1]

猜你喜欢

转载自blog.csdn.net/Kuroyukineko/article/details/82314937