美文网首页
7. Reverse Integer

7. Reverse Integer

作者: Double_E | 来源:发表于2017-04-05 15:09 被阅读38次

    Reverse digits of an integer.
    Example1: x = 123, return 321Example2: x = -123, return -321
    click to show spoilers.
    **Note:
    **The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
    Subscribe to see which companies asked this question.

    Python

    • 最简单翻转数字的方法 int(str(x)[::-1]
    • 注意这里如果超出范围[-2^31, 2^31]要置为0
    • 2^31 = 2147483648
    class Solution(object):
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            result = int(str(x)[::-1]) if x >= 0 else -1 * int(str(-x)[::-1])
            return result if result < 2147483648 and result > -2147483648 else 0
            
    

    相关文章

      网友评论

          本文标题:7. Reverse Integer

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