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: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
思路:(1)先判断正负,获取符号。
(2)小于10的正数可以直接输出。
(3)对10取余,通过余数进行操作。
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
symble=1
result=0
if x<0:
symble = -1
x= -x
if 0<=x<10:
return x
while x>=10:
a = x % 10
result = (result+a) * 10
x = (x-a)/10
result += x
if result < - 2**31 or result > 2**31-1 :
return 0
return symble*result