[LeetCode]7 整数反转

题目描述

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例1:

输入: 123
输出: 321

示例2:

输入: -123
输出: -321

示例3:

输入: 120
输出: 21

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x==0:
return 0
str_x = str(x)
x = ''
if str_x[0] == '-':
x += '-'
x += str_x[len(str_x)-1::-1].lstrip("0").rstrip("-")
x = int(x)
if -2**31<x<2**31-1:
return x
return 0