Description
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.
Answer - Beats 97.98%
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ if x >= 0 and x <= 2**31-1: list_a = list(str(x)[::-1]) expect = int(''.join(list_a)) if expect <= 2**31-1: return expect else: return 0 elif x < 0 and x >= (-2)**31: list_a = list(str(abs(x))[::-1]) expect = -1 * int(''.join(list_a)) return 0 if expect < (-2)**31 else expect else: return 0
摘录一个别人的两行答案,beats 97.98%:
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ n = int(str(abs(x))[::-1]) return 0 if x == 0 else ((x>0)-(x<0)) * n * (n < 2**31)
Python3的(x>0)-(x<0) 相当于python2的cmp().
# Python program to demonstrate the # use of cmp() method # when a<b a = 1 b = 2 print(cmp(a, b)) ==> -1 # when a = b a = 2 b = 2 print(cmp(a, b)) == > 0 # when a>b a = 3 b = 2 print(cmp(a, b)) ==> 1