题目说明
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循环方法方便快捷很多)
注意限制一下输入输出范围即可