每日一题 2019 - 05 - 12
题目:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Note:
- Division between two integers should truncate toward zero.
- The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.
Example 1:
1 | Input: ["2", "1", "+", "3", "*"] |
Example 2:
1 | Input: ["4", "13", "5", "/", "+"] |
Example 3:
1 | Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] |
解法:
这个题给出逆波兰式让完成后缀表达式的求值,关于逆波兰式的求值在数据结构中已经有接触过,也即使用数据结构栈就可以完成任务,思路就是遇到非运算符时候,把运算数依次存入栈中,遇到运算符依次弹出两个运算数完成运算,并把结果从新推入栈顶,但是这个题还有需要注意的地方:
- 遇到
'-'
时候,要判断是运算符减号还是负号; - 如果进行除法运算过程中遇到除数是 0 的情况,直接返回 0 ;
- 对两个数进行操作时候,存放计算结果时候需要使用
long long int
来保存计算结果防止溢出;
代码:
1 | class Solution { |