[LeetCode]easy - Reverse Integer - python

Problem Description:

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer, then return 0.

题目要求反转整数中的数字。

思路一:

首先判断原数字的正负,用flag记录一下。通过循环对10取余得到尾部数字,一步步乘10构造新的翻转后的整数。最后判断结果是否溢出,若溢出则输出0.

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x >= 0:
            flag = 1
        else:
            flag = -1
        x = abs(x)
        x_new = 0
        while(x):
            x_new = 10 * x_new + x % 10
            x = x // 10
        x_new = flag * x_new
        return x_new if x_new < 2147483648 and x_new >= -2147483648 else 0

结果如下。

 思路二:

利用Python的字符串切片 step=-1 操作来实现对整数的反转,反转后的字符串转换为整数后输出。

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x >= 0:
            flag = 1
        else:
            flag = -1
        x = abs(x)
        
        x_new = str(x)
        x_new = int(x_new[::-1])
            
        x_new = flag * x_new
        
        return x_new if x_new < 2147483648 and x_new >= -2147483648 else 0

结果如下:

 关于python切片的知识:

python切片对象的索引分为正索引和负索引两部分

 

完整的切片表达式包含两个 “ : ”,用于分隔三个参数 ( start_index、end_index、step )。当只有一个 “ : ” 时,默认第三个参数step=1;当一个 “ : ” 也没有时,start_index=end_index,表示切取start_index指定的那个元素。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值