3.反转整数-leetcode 007(python)

  • 题目描述

给定一个 32 位有符号整数,将整数中的数字进行反转。

  • 示例1

输入: 123
输出: 321


  • 示例2

输入: -123
输出: -321


  • 示例3

输入: 120
输出: 21


  • 注意

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。

  • 解决方案

使用分片操作[ : : -1] 翻转列表或字符串

  • 代码一
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        l = list(str(x))
        n = len(l)
        
        #寻找最靠后的不是0的数字
        for i in range(n-1,0,-1):
            if l[i] != '0':
                l = l[:i+1]
                break
            
        #如果是负数的话,反转之后要加上符号
        if l[0] == '-':
            l = l[:0:-1]
            l.insert(0,'-')
        else:
            l = l[::-1]
        x = int(''.join(l))
        
        #check the number
        if x<2147483648 and x >-2147483648:
            return x
        else:
            return 0
        
  • 代码二
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
       
        if x > 0:
            t_str = str(x)[::-1]
            t = int(t_str)
        else:
            t_str = str(-x)[::-1]
            t = -int(t_str)

        if t< 2147483648 and t >-2147483648:
            return t
        else:
            return 0

猜你喜欢

转载自blog.csdn.net/Try_my_best51540/article/details/82798109