整数反转(leetcode)

题目:

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

如果反转后整数超过 32 位的有符号整数的范围 −231, 231 − 1 ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:

输入:x = 123

输出:321

python 复制代码
class Solution:
    def reverse(self, x: int) -> int:
       x_str = str(x)
       x_str = x_str.strip('-')
       x_str = x_str.rstrip('0')
       x_str = x_str[::-1]
       if x < 0:
         x_str = '-' + x_str
       if not x_str:
         x_str = '0'
       result = int(x_str)
       if result < -2**31 or result > 2**31 - 1:
         return 0
       return result
相关推荐
Warson_L4 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅4 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅4 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L4 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅4 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L5 小时前
python的类&继承
python
Warson_L5 小时前
类型标注/type annotation
python
ThreeS7 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
金銀銅鐵9 小时前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏