美文网首页LeetCode
LeetCode-7 - Reverse Integer

LeetCode-7 - Reverse Integer

作者: 空即是色即是色即是空 | 来源:发表于2017-11-13 14:35 被阅读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]中的任意一个

    相关文章

      网友评论

        本文标题:LeetCode-7 - Reverse Integer

        本文链接:https://www.haomeiwen.com/subject/aalzmxtx.html