Skip to content

Commit 48db8be

Browse files
author
applewjg
committed
EvaluateReversePolishNotation
Change-Id: I371af5e39ef9577537e5118f287d75f3eb003664
1 parent 2c41774 commit 48db8be

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

EvaluateReversePolishNotation.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 31, 2015
4+
Problem: Evaluate Reverse Polish Notation
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
7+
Notes:
8+
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
9+
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
10+
Some examples:
11+
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
12+
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
13+
Solution: stack.
14+
*/
15+
16+
public class Solution {
17+
public int evalRPN(String[] tokens) {
18+
Stack<Integer> stk = new Stack<Integer>();
19+
for (int i = 0; i < tokens.length; ++i) {
20+
if ((tokens[i].compareTo("+") != 0) && (tokens[i].compareTo("-") != 0)
21+
&& (tokens[i].compareTo("*") != 0) && (tokens[i].compareTo("/") != 0)) {
22+
stk.push(Integer.parseInt(tokens[i]));
23+
} else {
24+
int op2 = stk.pop();
25+
int op1 = stk.pop();
26+
int res = 0;
27+
if(tokens[i].compareTo("+") == 0)
28+
res = op1 + op2;
29+
else if(tokens[i].compareTo("-") == 0)
30+
res = op1 - op2;
31+
else if(tokens[i].compareTo("*") == 0)
32+
res = op1 * op2;
33+
else if(tokens[i].compareTo("/") == 0)
34+
res = op1 / op2;
35+
stk.push(res);
36+
}
37+
}
38+
return stk.pop();
39+
}
40+
}

0 commit comments

Comments
 (0)