整数反转(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
相关推荐
cui_ruicheng2 小时前
Python从入门到实战(十六):多进程编程
开发语言·python
_Jimmy_3 小时前
FastAPI + SQLAlchemy全局事务管理
python·fastapi
用户8356290780513 小时前
如何使用 Python 在 Excel 中添加、编辑和删除超链接
后端·python
AC赳赳老秦5 小时前
企业工商公开信息采集分析:OpenClaw 批量查询企业工商信息,生成企业画像报告
大数据·开发语言·python·自动化·php·deepseek·openclaw
来一碗刘肉面6 小时前
栈的应用(表达式求值)
数据结构·算法
FoldWinCard6 小时前
D6 Python 基础语法 --- 保留关键字
开发语言·python
暮暮祈安6 小时前
Celery 新手入门指南
java·数据库·python·flask·httpx
JustNow_Man6 小时前
每日高频场景英文口语
python
xiaowang1234shs6 小时前
怪兽轻断食技术深度测评:从断食计时引擎到AI识别算法的工程实践解析
数据库·人工智能·算法·macos·机器学习·p2p·visual studio