# 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


## Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: $[−2^{31}, 2^{31} − 1]$. 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

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)


1. 未考虑到正负符号

2. 为考虑超出32位

3. 未考虑时间限制

1. list.reverse()方法

2. 字符串切片方法：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