【LeetCode-easy-7-Reverse Integer】-python

PROBLEM

Given a 32-bit signed integer, reverse digits of an integer.

EXAMPLES

Input: 123
Output:  321
Input: -123
Output: -321
Input: 120
Output: 21

题目解析

题目是将一个32位整数倒转,这在python里实现非常容易实现,使用数组的倒转即可。需要注意的有两点,①倒转后的数字可能大于32位整数的最大值;②是倒转时负号的处理。①的处理办法是当大于2的23次方或小于负的2的23次方时,返回0;②的处理办法是将负号去掉,对正数部分倒转后再加上。

CODE

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x >= 0:
            y = int(str(x)[::-1])
            if y <= pow(2, 31):
                return y
            else:
                return 0
        else:
            y = 0 - int(str(abs(x))[::-1])
            if y >= 0 - pow(2, 31):
                return y
            else:
                return 0

你可能感兴趣的:(【LeetCode-easy-7-Reverse Integer】-python)