zoukankan      html  css  js  c++  java
  • LeetCode 第七题: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

    二、解题思路

    首先我想到的是字符串的反转问题,利用栈进行,先把给定的整数转换成字符串,然后把元素压入栈,再一个个出栈,但是这样没法处理负数,比如:输入 -123,希望输出是 -321,我却输出了 321-,所以第一步得先做一个判断,看是否负数,负数的话,初始字符串应该是 ‘ - ’,而不是空字符串,这样看似解决了符号问题,但是在某些情况下,会溢出,比如给定的x为 :-2147483638,明显没有溢出,但是经过我的转化成 8363847412,就明显溢出了,所以得加判断,这是一处判断,还有一处是输出的时候需要加判断整数是否溢出。提交之后看到 AC,十分开心,但是看到别人的答案,瞬间崩溃了,别人用python的切片功能几行代码就解决了,我居然写了好多行,下附我的代码和别人的代码:

    先附上别人简洁的代码:

    def reverse1(self,x):
        if x < 0:
            y = -1*int(str(-x)[::-1])
        else:
            y = int(str(x)[::-1])
        if y > 2147483647 or y<-2147483648:
            y = 0
        print(y)
        return y
    

    下面是我用栈实现的代码:

    class Solution:
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            if x<0:
                outstr = '-'
                zx = -x
                if zx > 2147483647:
                    return 0
                strx = str(zx)
            else:
                outstr = ' '
                strx = str(x)
            s = Stack()
            for item in strx:
                s.push(item)
            while not s.is_empty():
                outstr += s.pop()
            y = int(outstr)
            if -2147483648 <= y < 2147483647:
                return y
            else:
                return 0
           
    class Stack(object):
        def __init__(self):
            self._elems = []
        def push(self,elem):
            self._elems.append(elem)
        def pop(self):
            return self._elems.pop()
        def is_empty(self):
            return self._elems == []
    View Code

    下面记录一下python中的切片操作

    if __name__ == '__main__':
        '''
        切片的对象是字符串,列表,元组对象,形式为 obj[start:end:step]
        切片的时候,开始的元素包括在结果之中,而结束的元素不包括在结果中,如下面的kf2输出为56,其计算过程是
        首先从k的第4个元素开始,即从5开始切,以步长为1开始直至找到k的第6个位置即7为止,但是不能包含7,所以就只输出56
        '''
        k = "123456789"
        "字符串反转"
        fk1 = k[::-1]
        fk2 = k[4:6:1]
        fk3 = k[8:3:-2]
        print(fk3)
    

      

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    Codeforces Round #594 (Div. 2) ABC题
    Codeforces Round #596 (Div. 2) ABCD题
    数据结构实验5——二叉树
    数据结构实验4——字符串匹配
    数据结构实验3——用栈求解算术表达式
    友链
    Codeforces Round #577 (Div. 2)
    Educational Codeforces Round 70 (Rated for Div. 2)
    Codeforces Round #578 (Div. 2)
    2020 Multi-University Training Contest 10(待补
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8578106.html
Copyright © 2011-2022 走看看