This code is about evaluation of Postfix expression using stack.
Main class
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
Solution r = new Solution();
System.out.println(r.evaluatePostFix(s));
}
}
Solution class
public class Solution {
public static int evaluatePostFix(String S) {
Stack<Character> st = new Stack<>();
int c1, c2;
int op = 0;
for (int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
switch(c) {
case '+':
c1 = (int) st.pop();
c2 = (int) st.pop();
op = c2 + c1;
st.push((char) op);
break;
case '-':
c1 = (int) st.pop();
c2 = (int) st.pop();
op = c2 - c1;
st.push((char) op);
break;
case '*':
c1 = (int) st.pop();
c2 = (int) st.pop();
op = c2 * c1;
st.push((char) op);
break;
case '/':
c1 = (int) st.pop();
c2 = (int) st.pop();
op = c2 / c1;
st.push((char) op);
break;
default:
st.push(c);
}
System.out.println(st);
}
return st.peek();
}
}
What's going wrong?
For input 345+*
, I got:
[3]
[3, 4]
[3, 4, 5]
[3, i]
[ᓫ]
5355
but 27 is expected!