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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
r = cmp(x, 0)*int(str(abs(x))[::-1])
return r if -2**31 < r < 2**31 - 1 else 0
一個更加精簡的solution
def reverse(self, x):
s = cmp(x, 0)
r = int(`s*x`[::-1])
return s*r * (r < 2**31)
反思/總結
- 反引號可以讓整型數字變成字符串
- 布爾類型的True實數部分為整數1,False實數部分為整數0,乘法會分別取值1,0
- cmp 內置函數可以返回[-1, 0, 1]中的任意一個