leetcode_7.整数反转python

完整代码及注释

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值