Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +
, -
, *
, /
operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: "3+2*2" Output: 7
Example 2:
Input: " 3/2 " Output: 1
Example 3:
Input: " 3+5 / 2 " Output: 5
把字符串转为数学公式进行计算。注意排除空格。
首先是获得完整的数字,可以用i.isdigit()或者i in ‘0123456789’来判断i是否是数字。
然后空格跳过。
注意符号对应的时挨着的后面的数字计算方式,所以在最前面添加一个‘+’,使后面每个数字对应正确的符号。
最后再随意添加一个符号,否则不会计算到原字符串中的最后一个符号。
除法需要特别注意,这里python3可运行,python会报错,因为除法取整的方式在python2.X和python3中是不同的。
class Solution:
def calculate(self, s: str) -> int:
stack=[]
num=0
s+='+'
pre='+'
for i in s:
if i in '0123456789':
num=num*10+int(i)
elif i==' ':
continue
else:
if pre=='+':
stack.append(num)
elif pre=='-':
stack.append(-num)
elif pre=='*':
prenum=stack.pop()
stack.append(prenum*num)
elif pre=='/':
prenum=stack.pop()
stack.append(int(prenum/num))
num=0
pre=i
return sum(stack)