您好,欢迎访问一九零五行业门户网

LeetCode 2 Evaluate Reverse Polish Notation

evaluate the value of arithmetic expression in reverse polish notation. valid operator are ,-,*,/. each operand may be an integer or another expression. some examples: [2, 1, , 3, *] - ((21)*3) - 9 [4, 13, 5, /, ] - (4 (13 / 5)) - 6 分析:
evaluate the value of arithmetic expression in reverse polish notation.
valid operator are +,-,*,/. each operand may be an integer or another expression.
some examples:
[2, 1, +, 3, *] -> ((2+1)*3) -> 9
[4, 13, 5, /, +] -> (4 + (13 / 5)) -> 6
分析:后缀表达式操作。
栈的应用,如果碰见数字,则压栈,碰见运算符则弹出两个元素,对两个元素进行数学运算后结果压栈。
public class solution { public int evalrpn(string[] tokens) { stack st = new stack(); for(string token : tokens){ if(token.matches(-?[0-9]+)){ st.push(integer.parseint(token)); }else{ int num2 = st.pop(); int num1 = st.pop(); if(token.equals(+)){ st.push(num1+num2); }else if(token.equals(-)){ st.push(num1-num2); }else if(token.equals(*)){ st.push(num1*num2); }else if(token.equals(/)){ st.push(num1/num2); } } } return st.pop(); }}
其它类似信息

推荐信息