#题解中将负的数取其相反数,最终将栈内所有数相加即可classSolution(object):defclumsy(self, N):
stack =[N]
top =0for i inrange(1, N):if i %4==0:
stack.append(i - N)
top +=1elif i %4==1:
stack[top]*=(N - i)elif i %4==2:
stack[top]=int(stack[top]/(N - i))elif i %4==3:
stack.append(N - i)
top +=1
ans =0for i in stack:
ans += i
return ans
if __name__ =='__main__':
x = Solution()print(x.clumsy(10))
在这里插入代码片
150.逆波兰表达式
之前考研学到的中缀表达式转后缀表达式,这里逆波兰其实就是前缀表达式
import math
classSolution(object):defevalRPN(self, tokens):
stack =[]for i in tokens:if i =="+":
stack[len(stack)-2]+= stack.pop()elif i =="-":
stack[len(stack)-2]-= stack.pop()elif i =="*":
stack[len(stack)-2]*= stack.pop()elif i =="/":
temp = stack.pop()
stack[len(stack)-1]=int(math.modf(stack[len(stack)-1]/ temp)[1])else:
stack.append(int(i))returnint(stack[0])if __name__ =='__main__':
x = Solution()
tokens =["10","6","9","3","+","-11","*","/","*","17","+","5","+"]print(x.evalRPN(tokens))