zoukankan      html  css  js  c++  java
  • 【Leetcode】7:整数反转(Python)

    我的方法很简单,使用str函数首先将int转化为str,然后将str放到一个栈当中进行栈的反转,最后对该栈进行处理,比如去掉0或者添加数字前面的"-"号,处理完之后将栈中的字符串拼接起来得到返回值即可,代码如下:

    class Solution:
        def reverse(self, x: int) -> int:
            newint=str(x)
            stack=[]
            ret_final=''
            for i in newint:
                stack.append(i)
            ret=[]
            i=len(stack)-1
            while i>-1:
                ret.append(stack[i])
                i-=1
            if ret[-1]=='-':
                ret.pop(-1)
                ret.insert(0,"-")
    
            if ret[0]=='0':
                ret.pop(0)
            string=''
            for j in ret:
                string=string+j
            if string=='':
                return 0
            if int(string)>2**31-1 or int(string)<-2**31:
                return 0
            return int(string)

     

  • 相关阅读:
    模板方法模式
    策略模式
    享元模式
    组合模式
    桥接模式
    外观模式
    代理模式
    装饰者模式
    适配器模式
    类之间的关联关系和依赖关系
  • 原文地址:https://www.cnblogs.com/geeksongs/p/13619746.html
Copyright © 2011-2022 走看看