您的位置:首页 > 编程语言 > Lua

evaluate-reverse-polish-notation java code

2017-10-15 09:12 387 查看
Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are+,-,*,/. Each operand may be an integer or another expression.

import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
if(tokens.length==0)
return 0;
Stack<Integer> stack = new Stack<Integer>();
for(int i=0;i<tokens.length;i++){
if(tokens[i].equals("+")||tokens[i].equals("-")||tokens[i].equals("*")||tokens[i].equals("/")){
if(tokens[i].equals("+")){
int temp;
int a = stack.pop();
int b = stack.pop();
temp=a+b;
stack.push(temp);
}
if(tokens[i].equals("-")){
int temp;
int b = stack.pop();
int a = stack.pop();
temp=a-b;
stack.push(temp);
}
if(tokens[i].equals("*")){
int temp;
int b = stack.pop();
int a = stack.pop();
temp=a*b;
stack.push(temp);
}
if(tokens[i].equals("/")){
int temp;
int b = stack.pop();
int a = stack.pop();
temp=a/b;
stack.push(temp);
}
}else{
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.peek();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息