-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostfix.java
More file actions
38 lines (37 loc) · 1.06 KB
/
Postfix.java
File metadata and controls
38 lines (37 loc) · 1.06 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
import java.util.*;
public class Postfix{
static int postfix(String expr){
Stack<Integer> st= new Stack<>();
for(int i=0;i<expr.length();i++){
char s = expr.charAt(i);
if(s >= '0' && s <= '9'){
st.push(s-'0');
}else{
int v1 = st.pop();
int v2 = st.pop();
switch(s){
case '+':{
st.push(v2+v1);
break;
}
case '-': {
st.push(v2-v1);
break;
}
case '*': {
st.push(v2*v1);
break;
}
case '/': {
st.push((v2 < v1) ? v1 / v2 : v2 / v1);
break;
}
}
}
}
return st.pop();
}
public static void main(String[] args) {
System.out.println(postfix("231*+9-"));
}
}