1. 程式人生 > >Leetcode練習 整數翻轉

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))