7. 整数反转(reverse)

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。

 

示例 1:

输入:x = 123
输出:321

示例 2:

输入:x = -123
输出:-321

示例 3:

输入:x = 120
输出:21

示例 4:

输入:x = 0
输出:0

 

提示:

    -231 <= x <= 231 - 1

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

题解1:

执行用时:36 ms, 在所有 Python3 提交中击败了81.27% 的用户

内存消耗:15 MB, 在所有 Python3 提交中击败了22.84% 的用户

通过测试用例:1032 / 1032

查看代码
class Solution:
    def reverse(self, x: int) -> int:
        flag = 1
        s = ""
        if x < 0:
            flag = -1
            s = str(x * flag)
        else:
            s = str(x)
        ls = list(s)
        ls.reverse()
        s = ''.join(ls)
        res = int(s) 
        return res * flag if 32>len(bin(res))-2 else 0

 

题解2:

执行用时:52 ms, 在所有 Python3 提交中击败了10.17% 的用户

内存消耗:14.8 MB, 在所有 Python3 提交中击败了82.47% 的用户

通过测试用例:1032 / 1032

查看代码
 import math
class Solution:
    def reverse(self, x: int) -> int:
        flag = 1
        s = ""
        if x < 0:
            flag = -1
            s = str(x * flag)
        else:
            s = str(x)
        ls = list(s)
        ls.reverse()
        s = ''.join(ls)
        res = int(s) * flag
        maxn = math.pow(2,31)
        return res if -1*maxn<=res and res<=maxn-1 else 0
posted @ 2022-07-13 18:18  tros  阅读(167)  评论(0)    收藏  举报