题目
基本计算器 II
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
整数除法仅保留整数部分。
示例 1:
输入:s = “3+2*2”
输出:7
示例 2:
输入:s = " 3/2 "
输出:1
示例 3:
输入:s = " 3+5 / 2 "
输出:5
提示:
1 <= s.length <= 3 * 105
s 由整数和算符 (’+’, ‘-’, ‘*’, ‘/’) 组成,中间由一些空格隔开
s 表示一个 有效表达式
表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1] 内
题目数据保证答案是一个 32-bit 整数
代码
先处理字符串里面的空格,如果有空格,则跳过,如果字符串里面的是数字则将数字存到num变量,当操作符为‘±’则将数字入栈,当操作符为‘*/’则将数字运算完再入栈。最后统计整个栈的数字之和。
class Solution:
def calculate(self, s: str) -> int:
size = len(s)
stack = []
index = 0
op='+'
while index<size:
if s[index]==' ':
index+=1
continue
if s[index].isdigit():
num=ord(s[index])-ord('0')
while index+1<size and s[index+1].isdigit():
index+=1
num=num*10+ord(s[index])-ord('0')
if op=='+':
stack.append(num)
elif op=='-':
stack.append(-num)
elif op=='*':
top=stack.pop()
num=num*top
stack.append(num)
elif op=='/':
top=stack.pop()
num=int(top/num)
stack.append(num)
elif s[index] in '+-*/':
op = s[index]
index+=1
return sum(stack)