完整代码及注释
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
//确定输入的数字是否为0
if x == 0:
return 0
//整数转化为字符串
str_x = str(x)
//置x为空串
x = ''
//是否为负数
if str_x[0] == '-':
x += '-'
//先将str_x字符串翻转,去掉末尾的'-'和前面的'0'
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
几个小知识点
对列表的操作:
1.列表的截取:
list = [1, 2, 3, 4, 5, 6, 7 ];
>>list[1:5]: [2, 3, 4, 5]
若[]里面的第二个冒号后的参数是:-1,即list[1:5:-1]: [5, 4,3, 2]
,以此来实现翻转
2.列表的.lstrip()
.rstrip()
:括号里的参数是想要过滤的字符。例如:
str = " this is string example....wow!!! ";
print str.lstrip();
str = "88888888this is string example....wow!!!8888888";
print str.lstrip('8');
输出
this is string example....wow!!!
this is string example....wow!!!8888888
3.整数转字符串、字符串转整数:str(x)/int(x)