-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode_02.java
53 lines (53 loc) · 1.3 KB
/
LeetCode_02.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class LeetCode_02 {
public int evalRPN(String[] tokens) {
Stack<Integer> s=new Stack<Integer>();
int num=0;
for(int i=0;i<tokens.length;i++)
{
try
{
int a=Integer.parseInt(tokens[i]);
s.push(a);
}
catch(Exception e)
{
if(tokens[i].equals("+"))
{
int a=s.pop();
int b=s.pop();
num=a+b;
s.push(num);
}
if(tokens[i].equals("-"))
{
int a=s.pop();
int b=s.pop();
num=b-a;
s.push(num);
}
if(tokens[i].equals("*"))
{
int a=s.pop();
int b=s.pop();
num=a*b;
s.push(num);
}
if(tokens[i].equals("/"))
{
int a=s.pop();
int b=s.pop();
num=b/a;
s.push(num);
}
}
}
if(!s.isEmpty())
num=s.pop();
return num;
}
public static void main(String[] args)
{
String[] tokens={"2", "1", "+", "3", "*"};
System.out.println(evalRPN(tokens));
}
}