Leetcode 7. Reverse Integer

Leetcode 7. Reverse Integer

题目说明

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

代码部分1

class Solution:
    def reverse(self, x: 'int') -> 'int':
        c = 1
        if x < 0:
            c = -1        
            x = x*c
        string = str(x)
        out = ''
        for i in range(len(string),-1,-1):
            out += string[i]
        return out

初级版本(想法思路方向很不完善,for循环用在这边也是特别的浪费时间空间)
没有考虑到输入输出的范围限制

代码部分2

class Solution:
    def reverse(self, x: 'int') -> 'int':
        if x>-2**31 and x<2**31-1:
            c = 1
            if x < 0:
                c = -1        
                x = x*c
            string = str(x)
            out = string[::-1]
            out = int(out)
            if out>-2**31 and out<2**31-1:
                return c*out
            else:
                return(0)
        else:
            return(0)

Runtime: 84 ms, faster than 23.51% of Python3 online submissions for Reverse Integer.

Memory Usage: 12.5 MB, less than 69.90% of Python3 online submissions for Reverse Integer.

主要思路:
获取Int输入,本身基于整数类型的区域操作太慢且复杂,直接类型转换为str(初期想过list有点麻烦就放弃了),在此之前通过c符号位解决正负问题;
str截取[::-1]获得反序列很方便(比for循环方法方便快捷很多)
注意限制一下输入输出范围即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值