LeetCode-7 - Reverse Integer

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]中的任意一个
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容