(python刷题)leetcode 第7题:整数反转

题目在leetcode上的链接为:
https://leetcode-cn.com/problems/reverse-integer/

题目描述
在这里插入图片描述
解题思路
先将整数转化为字符串,然后进行字符串的反转,再将反转后的字符串转化为整数即可。注意判断反转后的整数是否溢出。

ps:
1.在 python2 中,整数类型的范围与机器的位数有关,32位机器中整数类型的范围为 2 31 -2^{31} ~ 2 31 2^{31} -1,64位机器中整数类型的范围为 2 63 -2^{63} ~ 2 63 2^{63} -1,
而在 python3 中的整数 int 类型可以表示任意精度的整数,它可以表示的整数大小与机器的位数没有关系,只与机器的内存有关系。本文使用的是 python3 进行解题。
2.在 python3 中字符串的反转操作的两种常用的方法如下:
(1)使用切片操作进行字符串反转

s_reverse = s[::-1]

(2)借用列表的反转操作实现字符串的反转

l = list(s)
l.reverse()
s_reverse = ''.join(l)

本文使用了第一种方法。

复杂度分析:
由于需要进行切片操作,时间复杂度为 o(n),n为整数的长度
只需要创建几个固定数目的变量,空间复杂度为 o(1)

python代码:

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        flag = 1
        if x < 0:
            flag = -1
            x = abs(x)
        s = str(x)
        s_reverse = s[::-1]
        res = int(s_reverse) * flag
        if res >= pow(-2, 31) and res <= pow(2, 31) - 1:
            return res
        else:
            return 0
发布了37 篇原创文章 · 获赞 6 · 访问量 5396

猜你喜欢

转载自blog.csdn.net/qq_37891889/article/details/104232636