整数反转(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
相关推荐
写代码写到手抽筋4 小时前
5G上行DCI字段判定:端口 流数 PMI选择详解
java·算法·5g
曲幽4 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
xieliyu.4 小时前
Java算法精讲:双指针(二)
java·开发语言·算法
装不满的克莱因瓶4 小时前
掌握 RNN 与 LSTM 模型结构
人工智能·python·rnn·深度学习·神经网络·ai·lstm
何以解忧,唯有..5 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
wayz115 小时前
Momentum:PSL(心理线指标)技术指标详解
算法·金融·数据分析·量化交易·特征工程
金銀銅鐵5 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf5 小时前
Python 模块与包的导入导出
前端·后端·python
8Qi85 小时前
LeetCode 213:打家劫舍 II(House Robber II)—— 题解 ✅
算法·leetcode·职场和发展·动态规划
ice8130331816 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib