整数反转(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
相关推荐
patrickpdx几秒前
高联预赛中的高斯函数问题
算法
tkevinjd8 分钟前
力扣300-最长递增子序列
算法·leetcode·职场和发展·动态规划·贪心
用户2986985301431 分钟前
Python 实现 Excel 到 ODS、XPS、PostScript 及 PDF/A-1b 的格式转换
后端·python·excel
本地化文档37 分钟前
xlwings-docs-l10n
python·github·excel·gitcode·sphinx
梅雅达编程笔记1 小时前
零基础学 Python 第7章 | 字典 dict:键值对存储
开发语言·python·beautifulsoup·numpy·pandas
heroboyluck1 小时前
AI工程师第四课 - 深度学习入门
人工智能·python·深度学习·llama
小李飞刀李寻欢2 小时前
DeepSeek V3 版本模型结构分析
算法·大模型·deepseek
alicema11112 小时前
BRAIN 研究顾问(Research Consultant)兼职
python·量化
元Y亨H2 小时前
Python,单引号和双引号有何区别
python