LeetCode算法-7. Reverse Integer [easy]

Question:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:
Input: 123
Output: 321

Example 2:
Input: -123
Output: -321

Example 3:
Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [ − 2 3 1 , 2 3 1 − 1 ] [−2^31, 2^31 − 1] [231,2311]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

我的思路:

将x转为字符串,将字符串逆序再转为int即可。
需要考虑的几个点:

  1. 正负数问题:设置一个符号标记即可
  2. 正数的范围:必须要限制在32位有符号整数的范围内,即[ − 2 ∗ 31 , 2 3 1 − 1 -2*31,2^31-1 231,2311]
  3. x末尾0的处理:将str转为int时,会默认将前面的0去除掉。如 i n t ( ′ 000012 3 ′ ) int('0000123') int(0000123)的结果是123
class Solution:
    def reverse(self, x: int) -> int:
        sign = 1 if x >=0 else -1
        str1 = str(sign * x)
        y = int(str1[::-1]) * sign
        return y if -2147483648 < y < 2147483647 else 0

字符串逆序的方式:str1[::-1]表示从头到尾逆序读取

执行内存:40ms,击败60.08%用户
内存消耗:13.5MB,击败5.25%用户

经典思路:

一次次取余,将数字从末尾开始逐步放到高位上。

class Solution:
   def reverse(self, x: int) -> int:
        y,res = abs(x),0
        boundry = 2147483647 if x>0 else 2147483648
        while y != 0:
            res = res * 10 + y % 10
            if res > boundry :
                return 0
            y //= 10 # python中整除是//
        return res if x >0 else -res

执行内存:32ms,击败89.8%用户
内存消耗:13.5MB,击败5.25%用户

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值