Leetcode刷题笔记python-----反转整数

Leetcode刷题笔记python3

No.1


反转整数


题目要求:给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321
示例 2:

输入: -123
输出: -321
示例 3:

输入: 120
输出: 21
注意:

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

代码:

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        
        if x>0 or x==0:
            x=str(x)
            y=''
            for i in range(len(x)-1,-1,-1):
                y+=x[i]
            y=int(y)
            if y<2**31-1:
                return y
            else:
                return 0
        else:
            x=abs(x)
            x=str(x)
            y=''
            for i in range(len(x)-1,-1,-1):
                y+=x[i]
            y=int(y)
            y=-y
            if y>-2**31:
                return y
            else:
                return 0

讨了个巧,利用python把数值型转换成字符型然后反转,感觉自己好水啊!

你可能感兴趣的:(Leetcode)