LeetCode-Python-7. 整数反转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

思路:

简单的字符串处理。去除符号后转字符串反转再转int即可,记得判断有没有溢出。

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """

        flag = 0
        if x < 0:
            flag = 1
        if flag:
            s = str(x)[1:]
            s = s[::-1]
            x = -1 *int(s)            
        else:
            s = str(x)
            s = s[::-1]
            x = int(s)
            
        if x < -1 * 2 **31 or x > 2** 31 -1:
            return 0    
        return x

 

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        #2019.6.1
        INT_MIN = -2 **31
        INT_MAX = 2 ** 31 - 1
        op = 1
        if x < 0:
            op = -1
            s = str(x)[1:]
        else:
            s = str(x)
            
        res = op * int(s[::-1])
        return res if INT_MIN <= res <= INT_MAX else 0
            
        

 

你可能感兴趣的:(Leetcode)