Evaluate Reverse Polish Notation
Python在做除法时,全部是向下取整的,就是负数也是向下取整,而人正常的思维逻辑是绝对值向下取整,所以Python做这道题要小心除法的坑,Java不存在这个问题
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for token in tokens:
if token == '+':
addNum = stack.pop()
stack[-1] += addNum
elif token == '-':
minusNum = stack.pop()
stack[-1] -= minusNum
elif token == '*':
mul = stack.pop()
stack[-1] *= mul
elif token == '/':
dividend = stack.pop()
divisor = stack.pop()
if divisor == 0:
stack.append(0)
continue
tmp = abs(divisor) / abs(dividend)
tmp *= (abs(divisor) * abs(dividend) / (divisor * dividend))
stack.append(tmp)
else:
stack.append(int(token))
return stack[-1]
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack();
for (String token : tokens) {
if (token.equals("+")) {
int addNum = stack.pop();
int base = stack.pop();
stack.push(base + addNum);
} else if (token.equals("-")) {
int minusNum = stack.pop();
int base = stack.pop();
stack.push(base - minusNum);
} else if (token.equals("*")) {
int mul = stack.pop();
int base = stack.pop();
stack.push(mul * base);
} else if (token.equals("/")) {
int div = stack.pop();
int base = stack.pop();
stack.push(base / div);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
}