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 hold 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.
思路: 将负数取绝对值,都按正整数转化为列表,再将列表转化为正整数,如果x为负则再将所得结果y转化为负数。
1 class Solution(object): 2 def reverse(self, x): 3 """ 4 :type x: int 5 :rtype: int 6 """ 7 list = [] 8 a = abs(x) 9 y = 0 10 for i in range(len(str(a))): 11 i = a % 10 12 list.append(i) 13 a = a // 10 14 15 list.reverse() 16 17 for j in range(len(list)): 18 y = y + list[j]* 10 ** j 19 if x < 0: 20 y = 0 - y 21 22 if type(x) == type(y) == type(1):
#if -2147483648<x<2147483648 and -2147483648<y<2147483648 : 23 return y 24 else: 25 return 0