leetcode之整数反转(Python)

    科技2022-09-07  101

    参考链接:

    https://leetcode-cn.com/problems/reverse-integerhttps://leetcode-cn.com/problems/reverse-integer/solution/pythondan-chu-he-tui-ru-shu-zi-yi-chu-qian-jin-xin/

    题目描述

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

    示例 1:

    输入: 123 输出: 321

    示例 2:

    输入: -123 输出: -321

    示例 3:

    输入: 120 输出: 21

    注意:

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

    普通解法:

    主要使用Python中的str()和int(),注意边界和符号即可。

    def reverse_force(self, x: int) -> int: if -10 < x < 10: return x str_x = str(x) if str_x[0] != "-": str_x = str_x[::-1] x = int(str_x) else: str_x = str_x[:0:-1] x = int(str_x) x = -x return x if -2147483648 < x < 2147483647 else 0

    优化解法:

    每次取出整数x的最后一位,将其加入结果中。

    def reverse_better(self, x: int) -> int: y, res = abs(x), 0 # 则其数值范围为 [−2^31, 2^31 − 1] boundry = (1 << 31) -1 if x > 0 else 1 << 31 while y != 0: res = res * 10 + y % 10 if res > boundry: return 0 y //= 10 return res if x > 0 else -res

    时间复杂度: O ( l o g ( x ) ) O(log(x)) O(log(x)) x x x中大约有 l o g 10 ( x ) log10(x) log10(x)位数字。 空间复杂度: O ( 1 ) O(1) O(1)

    Processed: 0.008, SQL: 9