Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators is +,-, *,/. Each operand is an integer or another expression. For example:
["2", "1", "+", "3", "*")--((2 + 1) (3)-9 ["4", "", "5", "/", "+"], 4 + (13/5))
1. Naive approach
This problem can is solved by using a stack. We can loop through each element in the given array. When it's a number, push it to the stack. When it's an operator, pop the numbers from the stack, do the calculation, and push the result.
Public class Test {
Public Static void throws IOException {
New String[] {"2", "1", "+", "3", "*"};
System.out.println (EVALRPN (tokens));
}
Public Static int EVALRPN (string[] tokens) {
int returnvalue = 0;
String operators = "+-*/";
New Stack<string> ();
for (String T:tokens) {
if //push to Stack if it is a number
Stack.push (t);
Else {//pop numbers from stack if it 's an operator
int a = integer.valueof (Stack.pop ());
int b = integer.valueof (Stack.pop ());
Switch (t) {
Case "+":
Stack.push (string.valueof (A + b));
break;
Case "-":
Stack.push (string.valueof (b-a));
break;
Case "*":
Stack.push (String.valueof (A * b));
break;
Case "/":
Stack.push (string.valueof (b/a));
break;
}
}
}
returnvalue = integer.valueof (Stack.pop ());
return returnvalue;
}
}
Or
Public class Solution {
Public int EVALRPN (string[] tokens) {
int returnvalue = 0;
String operators = "+-*/";
New Stack<string> ();
for (String T:tokens) {
if (!operators.contains (t)) {
Stack.push (t);
}Else{
int a = integer.valueof (Stack.pop ());
int b = integer.valueof (Stack.pop ());
int index = operators.indexof (t);
Switch (index) {
Case 0:
Stack.push (string.valueof (a+b));
break;
Case 1:
Stack.push (string.valueof (b-a));
break;
Case 2:
Stack.push (string.valueof (a*b));
break;
Case 3:
Stack.push (string.valueof (b/a));
break;
}
}
}
returnvalue = integer.valueof (Stack.pop ());
return returnvalue;
}
}
Algorithm Evaluate Reverse Polish Notation