LeetCode

LeetCode-7 - Reverse Integer

2017-11-13  本文已影响6人  空即是色即是色即是空

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)

反思/总结

  1. 反引号可以让整型数字变成字符串
  2. 布尔类型的True实数部分为整数1,False实数部分为整数0,乘法会分别取值1,0
  3. cmp 内置函数可以返回[-1, 0, 1]中的任意一个
上一篇下一篇

猜你喜欢

热点阅读