7.整数反转
方法一:
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
str_x = str(x)
if -10 < x < 10:
return x
elif x >= 10:
rev_x = int(str_x[::-1])
if rev_x >= 2147483648:
return 0
else:
return rev_x
elif x <= -10:
rev_x = int('-'+str_x[:0:-1])
if rev_x < -2147483648:
return 0
else:
return rev_x
a = Solution()
a.reverse(-123)
方法二:
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if -10 < x < 10:
return x
a,b = abs(x),0
# abs 表示返回绝对值
while a > 0:
b = b * 10 + a % 10
a = a // 10
if b>= 2147483648 or b < -2147483648:
return 0
else:
if x < 0:
return -b
elif x > 0:
return b
a = Solution()
print(a.reverse(-123))