整数反转(Python,LeetCode)

目录

题目描述

解决方案

代码

代码走读

传送门


题目描述

给出一个32位的有符号整数,你需要将这个整数中每位上的数字反转。对于溢出32位的数字则返回0。

输入/输出描述

输入 321
输出 123

解决方案

题目较为简单,需要在两个地方注意:

  • 输入的数字可能是负数。负数反转后还是负数
  • 反转后的数字如果超出32位,则需要返回0

代码

class Solution:
    def reverse(self, x: int) -> int:
        positive = True
        if x < 0:
            positive = False
            x = -x

        x = int(str(x)[::-1])
        if not positive:
            x = -x

        if self.out_of_range(x):
            return 0
        else:
            return x

    @staticmethod
    def out_of_range(x: int) -> bool:
        return x > 2 ** 31 - 1 or x < -2 ** 31

代码走读

class Solution:
    def reverse(self, x: int) -> int:
        # 先判断x正负性。记录后将x统一转换成正数(方便逆序)
        positive = True
        if x < 0:
            positive = False
            x = -x

        # 逆序,再根据之前的正负性记录还原x
        x = int(str(x)[::-1])
        if not positive:
            x = -x

        # 判断x是否溢出32位
        if self.out_of_range(x):
            return 0
        else:
            return x

    @staticmethod
    def out_of_range(x: int) -> bool:
        return x > 2 ** 31 - 1 or x < -2 ** 31

传送门

LeetCode试题链接

str()函数

int()函数

猜你喜欢

转载自blog.csdn.net/TCatTime/article/details/107750869