原题:
Given a 32-bit signed integer, reverse digits of an integer.
给定一个 32 位有符号整数,将整数中的数字进行反转。
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: . For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
My solution
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x >= -9 and x <= 9:
return x
self.output = ""
if x >= 0:
self.helper(x)
if self.output < -2**31 or self.output > 2**31 -1:
return 0
else:
x = -x
self.helper(x)
self.output = - self.output
if self.output < -2**31 or self.output > 2**31 -1:
return 0
return self.output
def helper(self, x):
mark = 0
while x:
remainder = x % 10
quotient = int(x / 10)
x = quotient
self.output += str(remainder)
mark += 1
# self.output = round(self.output * (10 ** (mark - 1)))
self.output = int(self.output)
# return output
Reference solution
开始的开始,我们都是孩子!一开始想到了本科学c的时候遇到过类似的,第一反应是通过除法取商和取模运算进行反转,即依次获取每一个位置的数,然后反转再输出。这里值得一提的是不需要像小詹最初所想的进行列表化再反转处理。按照下列代码逻辑,已经实现了反转。
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
#定义一个空字符串,思路是将数字字符化通过以下计算反转,
#转换成字符串后反转转换成数字
s = ''
while x//10 != 0:
num = x % 10
s = s + str(num)
x //= 10
s = s + str(x) #针对最高位或者本身就是个位数的特殊情况
return int(s)
然而,执行只能通过部分样例,检查发现有这样几种错误:
未考虑到正负符号
为考虑超出32位
未考虑时间限制
这题很简单,完善下逻辑肯定没问题,但是时间很容易超出限制。但是!我们是用啥?用的是python啊,就像之前打卡群里小伙伴说的python内置函数都很牛逼。这题就可以有python的独特方法实现噢,比如列表的反转方法有哪些?自行温习,这里小詹跟大家说两种常用的:
list.reverse()方法
字符串切片方法:res = s[::-1]
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
#先记录正负
sign = [1,-1][x < 0]
#利用正负反转后符号不变,并利用绝对值函数进行反转,添加原有符号即可
rst = sign * int(str(abs(x))[::-1])
#返回反转值,超出32位为0
return rst if -(2**31)-1 < rst < 2**31 else 0
这题思路简单,粗暴有力,尤其是利用python来实现简直就像是在作弊~~~~
注:代码中关sign = [1, -1][x < 0]这种用法,x为正,则 x<0 不满足条件,对应sign=1;x为负,则 x<0 满足条件,对应sign=-1 。以及python自带的list.reverse()方法和字符串切片方法:res = s[::-1]