leetcode 7. Reverse Integer(python)

该博客讨论了如何在32位整数范围内反转一个数,并处理可能的溢出问题。提供了一个Python解决方案,使用字符串操作实现反转,并检查反转后的数值是否在有效范围内。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321	

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

Note:

-2^31 <= x <= 2^31 - 1

解析

根据题意,就是找出将 x 的每一个数字逆序排列,且正负相同的数字,且转换之后的数字在 [-2^31, 2^31 - 1] 之间,且不以 0 为前置的字符串,否则为 ‘0’ 。

解答

 class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        r = '0'
        if x == 0:
            return r
        if x > 0:
            r = str(x)[::-1].lstrip("0")
        else:
            r = "-" + str(abs(x))[::-1].lstrip("0")
        if -(2 ** 31) > int(r) or int(r) > (2 ** 31) - 1:
            return '0'
        return r           	      

运行结果

Runtime: 12 ms, faster than 97.90% of Python online submissions for Reverse Integer.
Memory Usage: 13.5 MB, less than 33.78% of Python online submissions for Reverse Integer.

原题链接:https://leetcode.com/problems/reverse-integer/

您的支持是我最大的动力

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王大丫丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值