leetcode—— Reverse Integer

要求:给定一个32位有符号整数,取反。

例子:Input: 123 Output: 321

           Input: -123 Output: -321

          Input: 120 Output: 21

思路一:通过数字取反,首先需要判断正负

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

思路二:通过字符串切片输出

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

tips:

   字符串切片:list[start:end:step]

   例如:list=[1,2,3,4,5,6,7,8,9]

              list[1:3:1]='2,3'

猜你喜欢

转载自blog.csdn.net/qq_37386541/article/details/82080416