ericpuwang

整数反转

https://leetcode.cn/problems/reverse-integer/description/

给你一个32位的有符号整数x,返回将x中的数字部分反转后的结果 如果反转后整数超过32位的有符号整数的范围[−2^31, 2^31−1],就返回0 假设环境不允许存储64位整数(有符号或无符号)

示例1

输入:x = 123
输出:321

示例2

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

示例3

输入:x = 120
输出:21

示例4

输入:x = 0
输出:0
# python字符串反转
class Solution:
    def reverse(self, x: int) -> int:
        if -10 < x < 10:
            return x

        right = (1<<31) - 1
        left = -(right+1)
        str_x = str(x)
        if str_x[0] == '-':
            str_x = str_x[:0:-1]
            x = int(str_x)
            x = -x
        else:
            str_x = str_x[::-1]
            x = int(str_x)
        return x if left < x < right else 0