您的位置:首页 > 其它

leetcode--整数反转

2019-05-06 18:12 621 查看

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

示例 1:

输入: 123输出: 321

 示例 2:

输入: -123输出: -321

示例 3:

输入: 120输出: 21

注意:

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

class Solution:
    def reverse(self, x: int) -> int:
        if x > 0:
            xstr = str(x)
            if not xstr.endswith('0'):
                xlist = list(xstr)
                xlist.reverse()
                x = int(''.join(xlist))
            else:
                xlist = list(xstr)
                xlist.pop()
                xlist.reverse()
                x = int(''.join(xlist))
            if x > pow(2, 31):
                return 0
            else:
                return x
        elif x == 0:
            return x

        else:
            x = x.__abs__()
            xstr = str(x)
            if not xstr.endswith('0'):
                xlist = list(xstr)
                xlist.reverse()
                x = int(''.join(xlist))
            else:
                xlist = list(xstr)
                xlist.pop()
                xlist.reverse()
                x = int(''.join(xlist))
            if x > pow(2, 31):
                return 0
            else:
                return 0-x

执行用时 : 56 ms, 在Reverse Integer的Python3提交中击败了98.51% 的用户

内存消耗 : 13.1 MB, 在Reverse Integer的Python3提交中击败了90.48% 的用户


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: