leetcode7给定一个 32 位有符号整数,将整数中的数字进行反转。
python语言
#最通俗易懂的解法
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x>0:#输入x大于0
new_x=0
while(x>0):
value=x%10
x=int(x/10)
new_x=new_x*10+value
if new_x>=-2**31 and new_x<=2**31-1:#判断溢出
return new_x
else:
return 0
elif x<0:
new_x=0
x=-x
while(x>0):
value=x%10
x=int(x/10)
new_x=new_x*10+value
if new_x>=-2**31 and new_x<=2**31-1:
return -new_x
else:
return 0
else:
return 0
#利用python切片
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x=str(x)#转换成字符
if x[0]=='-':#为负时
x=x[1:]#从第一个数字开始取
new_x='-'+x[::-1]#翻转
else:
new_x=x[::-1]
new_x=int(new_x)
if new_x>=-2**31 and new_x<=2**31-1:
return new_x
else:
return 0