Leetcode07-整数反转

思路一:整数转化成字符串,字符串反转,最后再转化成整数

细节:如果是负数,负号需要单独处理。

python 复制代码
class Solution:
    def reverse(self, x: int) -> int:
        if x < 0:
            x = str(x)[1:]
            x = x[::-1]
            x = '-' + x
        else:
            x = str(x)
            x = x[::-1]
        if int(x) > 2**31-1 or int(x) < -2**31:
            return 0
        else:
            return int(x)

思路2:利用整除和取余运算符

细节:需要区分正数和负数,可以引入一个flag标记,如果为正数,flag=1;如果为负数,flag=-1.

python 复制代码
class Solution:
    def reverse(self, x: int) -> int:
        res = 0
        flag = 1
        if x < 0:
            flag=-1
            x = -x
        while x != 0:
            res = res * 10 + x % 10
            x //= 10
        if res < -2**31 or res > 2**31-1:
            return 0
        return res* flag
相关推荐
ytttr87314 分钟前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab
jianfeng_zhu2 小时前
整数数组匹配
数据结构·c++·算法
smj2302_796826522 小时前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
LYFlied3 小时前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
唯唯qwe-3 小时前
Day23:动态规划 | 爬楼梯,不同路径,拆分
算法·leetcode·动态规划
做科研的周师兄4 小时前
中国土壤有机质数据集
人工智能·算法·机器学习·分类·数据挖掘
来深圳4 小时前
leetcode 739. 每日温度
java·算法·leetcode
yaoh.wang4 小时前
力扣(LeetCode) 104: 二叉树的最大深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
hetao17338374 小时前
2025-12-21~22 hetao1733837的刷题笔记
c++·笔记·算法
醒过来摸鱼5 小时前
递归三种分类方法
算法