Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.9 kB
2
Indexable
Never
import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String exp = br.readLine();
        Solution ob = new Solution();
        ob.evaluate(exp);
    }
}

class Solution {
    int Evaluatepostfix(String postfix) {
        int n=postfix.length();
        Stack<Integer> st=new Stack<>();
        for(int i=0;i<n;i++) {
            char ch=postfix.charAt(i);
            if(Character.isDigit(ch)) {
                st.push(ch-'0');
            } else {
                int op1 = st.empty() ? 0 : st.pop();
                int op2 = st.empty() ? 0 : st.pop();
                if(ch=='+')st.push(op1+op2);
                else if(ch=='-')st.push(op2-op1);
                else if(ch=='/')st.push(op2/op1);
                else if(ch=='*')st.push(op2*op1);
            }
        }
        return st.peek();
    }
    String infixtopostfix(String infix) {
        String result=" ";
        int n=infix.length();
        Stack<Character> st=new Stack<>();
        for(int i=0;i<n;i++) {
            char ch=infix.charAt(i);
            if(Character.isLetterOrDigit(ch)) {
                result=result+ch;
            } else if(ch=='(') {
                st.push(ch);
            } else if(ch==')') {
                while(st.size()>0 && st.peek()!='(') {
                    result=result+st.peek();
                    st.pop();
                }
                st.pop();
            } else {
                while(st.size()>0 && prec(ch)<=prec(st.peek())) {
                    result=result+st.peek();
                    st.pop();
                }
                st.push(ch);
            }
        }
        while(st.size()>0) {
            result=result+st.peek();
            st.pop();
        }
        return result;
    }
    int prec(char ch) {
        if(ch=='^') return 3;
        else if(ch=='+'||ch=='-') return 1;
        else if(ch=='*'||ch=='/') return 2;
        else return -1;
    }
    String posttoprefix(String postfix) {
        Stack<String> st=new Stack<>();
        int n=postfix.length();
        for(int i=0;i<n;i++) {
            char ch=postfix.charAt(i);
            if(ch=='*'||ch=='/'||ch=='+'||ch=='-') {
                String op1=st.pop();
                String op2=st.pop();
                String res= ch + op2 + op1;
                st.push(res);
            } else {
                st.push(ch + "");
            }
        }
        return st.peek();
    }
    public void evaluate(String exp) {
        String postfix=infixtopostfix(exp);
        System.out.println(Evaluatepostfix(postfix));
        System.out.println(postfix);
        System.out.print(posttoprefix(postfix));
    }
}