整数反转(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
相关推荐
海底火旺几秒前
破解二维矩阵搜索难题:从暴力到最优的算法之旅
javascript·算法·面试
逢生博客34 分钟前
使用 Python 项目管理工具 uv 快速创建 MCP 服务(Cherry Studio、Trae 添加 MCP 服务)
python·sqlite·uv·deepseek·trae·cherry studio·mcp服务
堕落似梦41 分钟前
Pydantic增强SQLALchemy序列化(FastAPI直接输出SQLALchemy查询集)
python
黄昏ivi1 小时前
电力系统最小惯性常数解析
算法
独家回忆3641 小时前
每日算法-250425
算法
烁3471 小时前
每日一题(小白)模拟娱乐篇33
java·开发语言·算法
坐吃山猪2 小时前
Python-Agent调用多个Server-FastAPI版本
开发语言·python·fastapi
Demons_kirit2 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行2 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
永远在Debug的小殿下2 小时前
查找函数【C++】
数据结构·算法