7. 反转整数

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

示例:

输入: 123
输出: 321

输入: -123
输出: -321

输入: 120
输出: 21

注意:
假设我们的环境只能存储 32 位有符号整数,其数值范围是 \([−2^{31}, 2^{31} − 1]\)。根据这个假设,如果反转后的整数溢出,则返回 0。

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        str_x = str(x)
        num = 0
        
        if str_x[0] == "-":
            num = -int(str_x[1:][::-1])
        else:
            num = int(str_x[::-1])
            
        return num if num <= 2**31-1 and num >= -2**31 else 0
posted @ 2018-07-19 13:06  yuyin  阅读(68)  评论(0编辑  收藏  举报