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.
code:
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
str_ = str(abs(x))[::-1]
i = 0
while i < len(str_) and str_[i] == '0':
i += 1
if x > 0 and int(str_[i:]) < pow(2,31):
return int(str_[i:])
elif x < 0 and int('-'+str_[i:]) >= -pow(2,31):
return int('-'+str_[i:])
else:
return 0
tips:
1.
[::-1]反转string
2.
判断string的元素是否为0的时候,记得用‘0’
3.
仔细看note,如:本例的overflow
4.
输出时,注意转换数据类型