• LeetCode专题-Python实现之第7题:Reverse Integer


    导航页-LeetCode专题-Python实现

    相关代码已经上传到github:https://github.com/exploitht/leetcode-python
    文中代码为了不动官网提供的初始几行代码内容,有一些不规范的地方,比如函数名大小写问题等等;更合理的代码实现参考我的github repo

    1、读题

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return -321
    

    Note:
    The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

    这道题要求输入123返回321
    输入-123返回-321
    考虑32位有符号整型,溢出返回0

    2、解题

    看到逆序首先想到Python的各种序列类型可以轻松逆序,但是整型没有逆序的方法,咋办呢?转换成序列逆序然后转回来嘛,无非中间需要考虑正负号,考虑溢出。于是有了如下代码:

    class Solution(object):
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            # 将x的绝对值转换成字符串,逆序后转回整型数字
            rev = int(str(abs(x))[::-1])
            # 判断x和x转换后的结果是否能够不溢出,溢出则返回0
            if abs(x) > pow(2, 31) or abs(rev) > pow(2, 31):
                return 0
            # 返回结果,如果x本身是负数,那么当前数字也变成负数
            return rev if x > 0 else -rev
    

    3、第二种解题思路

    上面是通过py的序列反转来实现的,想想要不是py如此强大,某些语言可不能这样玩,比较常规的思路还是直接对数字操作,一位一位处理,于是有了如下解法

    class Solution(object):
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            
            y = 0
            tmp_x = abs(x)
            maxint = pow(2, 31)
            while tmp_x:
                # y不断进行当前位进10,拼接x低位的操作,这样x的最低位也就到了y的最高位
                y = y * 10 + tmp_x % 10
                # x要做的就是不断把个位拿出来
                tmp_x = tmp_x / 10
            if y > maxint or x > maxint:
                return 0
            return y if x > 0 else -y
    
  • 相关阅读:
    【poj1008】Maya Calendar
    【CodeVS4093】EZ的间谍网络
    2016.6.19 模拟考试
    【poj1129】Channel Allocation
    【poj2676】Sudoku
    Java 2D API
    Java 2D API
    IntelliJ IDEA
    IntelliJ IDEA 使用说明(For Eclipse user)
    IntelliJ IDEA
  • 原文地址:https://www.cnblogs.com/cloudgeek/p/7581852.html
Copyright © 2020-2023  润新知