用Python3实现LeetCode算法题系列——No.07 Reverse Integer [Easy]

版权声明:转载请注明来源! https://blog.csdn.net/CAU_Ayao/article/details/82084153

目录


1. 题目

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

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


2. 提交的代码

flag = 1
        if x <0:
            flag = -1
            x = -x
        xx = str(x)[::-1]
        xx = int(xx)
        if xx > 2147483647 or xx < -2147483648:
            xx = 0
        return xx * flag

3. 运行效果

这里写图片描述
这里写图片描述


4. 完整代码

class Solution:
    def reverse(self, x):
        flag = 1
        if x <0:
            flag = -1
            x = -x
        xx = str(x)[::-1]
        xx = int(xx)
        if xx > 2147483647 or xx < -2147483648:
            xx = 0
        return xx * flag

        """
        :type x: int
        :rtype: int
        """
def main():
    import sys
    def readlines():
        for line in sys.stdin:
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            x = int(line);

            ret = Solution().reverse(x)

            out = str(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/CAU_Ayao/article/details/82084153