LeetCode_Everyday:007 Reverse Integer

LeetCode_Everyday:007 Reverse Integer


LeetCode Everyday:坚持价值投资,做时间的朋友!!!

题目:

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
注意:假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为[231,2311][-2^{31},2^{31}-1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

示例:

  • 示例1
    输入: 123
    输出: 321
    
  • 示例2
    输入: -123
    输出: -321
    
  • 示例3
    输入:120
    输出:21
    

代码

方法一: 字符转换

执行用时 :52 ms, 在所有 Python3 提交中击败了25.21%的用户
内存消耗 :13.7 MB, 在所有 Python3 提交中击败了6.67%的用户

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        strx = str(x)
        x = int('-' + strx[1:][::-1]) if x<0 else int(strx[::-1])
        return  0 if x<-2**31 or x>2**31-1 else x
    
"""
For Example:    input:   x = -123
               output:   -321
"""
x = -123
                
solution = Solution()
result = solution.reverse(x)
print('输出为:', result)   # -321

方法二: 数学推算

执行用时 :32 ms, 在所有 Python3 提交中击败了98.25%的用户
内存消耗 :13.5 MB, 在所有 Python3 提交中击败了6.67%的用户

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        flag = -1 if x<0 else 1
        x = abs(x)
        res = 0
        while x:
            res = res*10 + x%10
            x //= 10
        res *= flag
        return 0 if res<-2**31 or res>2**31-1 else res
    
"""
For Example:    input:   x = -123
               output:   -321
"""
x = -123
                
solution = Solution()
result = solution.reverse(x)
print('输出为:', result)   # -321

参考

  1. https://www.bilibili.com/video/BV1tp411A7Eu?from=search&seid=13251925464525554525

此外

  • 原创内容转载请注明出处
  • 请到我的GitHub点点 star
  • 关注我的 CSDN博客
  • 关注公众号:CV伴读社

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章