整数反转(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
相关推荐
m0_734949794 小时前
MySQL如何配置定时清理过期备份文件_find命令与保留周期策略
jvm·数据库·python
m0_514520575 小时前
MySQL索引优化后性能没提升_通过EXPLAIN查看索引命中率
jvm·数据库·python
H Journey5 小时前
Python 国内pip install 安装缓慢
python·pip·install 加速
kobesdu5 小时前
人形机器人SLAM:技术挑战、算法综述与开源方案
算法·机器人·人形机器人
Polar__Star6 小时前
如何在 AWS Lambda 中正确使用临时凭证生成 S3 预签名 URL
jvm·数据库·python
m0_743623926 小时前
React 自定义 Hook 的命名规范与调用规则详解
jvm·数据库·python
FreakStudio7 小时前
无硬件学LVGL—定时器篇:基于Web模拟器+MicroPython速通GUI开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
椰羊~王小美7 小时前
随机数概念及算法
算法
阿Y加油吧7 小时前
算法实战笔记:LeetCode 169 多数元素 & 75 颜色分类
笔记·算法·leetcode
gCode Teacher 格码致知7 小时前
Python提高:pytest的简单案例-由Deepseek产生
python·pytest