题目:
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
Example 1:
Input: s = “3+2*2”
Output: 7
class Solution:
def calculate(self, s: str) -> int:
tmp_stack = []
cur_num = 0
pre_ope = '+'
for i in range(len(s)):
if s[i] != ' ' and s[i].isdigit():
cur_num = cur_num * 10 + int(s[i])
if i == (len(s)-1) or s[i] in '+-*/':
if pre_ope == '+':
tmp_stack.append(cur_num)
elif pre_ope == '-':
tmp_stack.append(-cur_num)
elif pre_ope == '*':
tmp_stack.append(tmp_stack.pop() * cur_num)
else:
tmp_stack.append(int(tmp_stack.pop() / cur_num))
pre_ope = s[i]
cur_num = 0
return sum(tmp_stack)
这里有两个点要注意:
- 刚开始我的代码里有一行continue,这个代码在我的笔记本上运行是没有问题的,但是在LeetCode上提交会报错,我是对比官方的答案才发现这一问题的,所以以后还是少用continue
if s[i] != ' ':
continue
- 因为题目里要求的是返回的是int型,所以我想当然地把除号/换成了整除号//,然后提交一直报错。
查了好久才发现问题所在。要注意的是:int()是直接向下取整的,当两个数相除时,如果两个数是证正数,那么整数除法和int()函数得到的结果一样,但是当两个数有一个为负数时,用int()函数得到的结果就会和整除运算得到的结果相差1,这是因为:
>>> -3//2
>>> -2
>>> int(-3/2)
>>>> -1