-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefixEvalution.java
43 lines (34 loc) · 1.03 KB
/
prefixEvalution.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
import java.util.Stack;
public class prefixEvalution {
public static int prefixEvalu(String s) {
Stack<Integer> st=new Stack<Integer>();
for(int i=s.length()-1 ; i>=0 ; i--){
char c=s.charAt(i);
if(c>='0' && c<='9'){
st.push(c-'0');
}else{
int op1=st.pop();
int op2=st.pop();
switch (c) {
case '+':
st.push(op1+op2);
break;
case '-':
st.push(op1-op2);
break;
case '*':
st.push(op1*op2);
break;
case '/':
st.push(op1/op2);
break;
}
}
}
return st.pop();
}
public static void main(String[] args) {
String s="-+7*45+20";
System.out.println(prefixEvalu(s));
}
}