Leetcode练习 整数翻转

# Reverse digits of an integer.
#
# Example1: x = 123, return 321
# Example2: x = -123, return -321
#
# click to show spoilers.
# Note:
# The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
# Subscribe to see which companies asked this question.

# 输入一个32位的有符号整数,返回该数字的翻转部分(不包括符号),如果翻转之后超出32位的范围就返回0

class Solution(object):
    def reverse(self, num):
        num = str(num)
        if num[0] == '-':
            num = '-' + num[1:][::-1]
        else:
            num = num[::-1]
        num = int(num)
        if num < -2147483648 or num > 2147483647:
            return 0
        else:
            return num

if __name__ == '__main__':
    num = -1235679
    s = Solution()
    print(s.reverse(num))

你可能感兴趣的:(Leetcode)