LeetCode--Reverse Integer(整数反转)Python

题目:

给定一个整数,返回反转后的整数。如给定12,返回21,给定210返回12,给定-231返回-132.

解题思路:

将整数先转为字符串格式。再倒序对字符串进行读取。

代码(Python):

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        # if x<-2^31 or x>2^31-1:
        #     return 0
        count = 0
        s = str(x)
        if s[0]=='-':
            for i in range(len(s)-1):
                count = count*10+int(s[-1-i])
            if count>2**31:
                return 0
            return -count
        else:
            for i in range(len(s)):
                count = count*10+int(s[-i-1])
            if count>2**31-1:
                return 0
            return count

你可能感兴趣的:(LeetCode)