-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path150.java (Stack 2)
More file actions
40 lines (40 loc) · 1.14 KB
/
150.java (Stack 2)
File metadata and controls
40 lines (40 loc) · 1.14 KB
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
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> s=new Stack<>();
for(String str: tokens){
if(str.equals("+")){
if(s.size()>=2){
Integer n2=s.pop();
Integer n1=s.pop();
Integer ans=n2+n1;
s.push(ans);}
}
else if(str.equals("-")){
if(s.size()>=2){
Integer n2=s.pop();
Integer n1=s.pop();
Integer ans=n1-n2;
s.push(ans);}
}
else if(str.equals("*")){
if(s.size()>=2){
Integer n2=s.pop();
Integer n1=s.pop();
Integer ans=n2*n1;
s.push(ans);}
}
else if(str.equals("/")){
if(s.size()>=2){
Integer n2=s.pop();
Integer n1=s.pop();
Integer ans=n1/n2;
s.push(ans);}
}
else{
Integer n=Integer.parseInt(str);
s.push(n);
}
}
return s.pop();
}
}