整数反转(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
相关推荐
人工智能训练18 小时前
【极速部署】Ubuntu24.04+CUDA13.0 玩转 VLLM 0.15.0:预编译 Wheel 包 GPU 版安装全攻略
运维·前端·人工智能·python·ai编程·cuda·vllm
yaoming16818 小时前
python性能优化方案研究
python·性能优化
码云数智-大飞19 小时前
使用 Python 高效提取 PDF 中的表格数据并导出为 TXT 或 Excel
python
biuyyyxxx20 小时前
Python自动化办公学习笔记(一) 工具安装&教程
笔记·python·学习·自动化
极客数模20 小时前
【2026美赛赛题初步翻译F题】2026_ICM_Problem_F
大数据·c语言·python·数学建模·matlab
A_nanda21 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
小鸡吃米…1 天前
机器学习中的代价函数
人工智能·python·机器学习
Li emily1 天前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
代码雕刻家1 天前
2.4.蓝桥杯-分巧克力
算法·蓝桥杯
m0_561359671 天前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python