Untitled
unknown
plain_text
3 years ago
3.6 kB
9
Indexable
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{
static int opVal(Character ch){
if(ch == '+')
return 1;
else if(ch == '-')
return 1;
else if(ch == '*')
return 2;
else
return 2;
}
static int value(int n1 , int n2 , Character ch){
if(ch == '+')
return n1+n2;
if(ch == '-')
return n1-n2;
if(ch == '*')
return n1*n2;
else
return n1/n2;
}
static String post(String exp){
// System.out.println(exp);
Stack<String> num = new Stack<>();
Stack<Character> op = new Stack<>();
for(int i = 0 ; i < exp.length() ; i++){
char ch = exp.charAt(i);
if(ch == '(')
op.push(ch);
else if(Character.isDigit(ch)){
num.push(ch+"");
}
else if(ch == ')'){
while(op.size() != 0 && op.peek() != '('){
String b = num.pop();
String a = num.pop();
String ans = a + b + op.pop();
num.push(ans);
}
op.pop();
}
else {
op.push(ch);
}
}
// System.out.println(num);
// while(op.size() != 0){
// ans += op.pop();
// }
while(num.size() > 0 && op.size() > 0){
String b = num.pop();
String a = num.pop();
String ans = a + b + op.pop();
num.push(ans);
}
String ans = num.pop();
return ans;
}
static String pre(String exp){
Stack<String> num = new Stack<>();
Stack<Character> op = new Stack<>();
for(int i = 0 ; i < exp.length() ; i++){
char ch = exp.charAt(i);
if(ch == '(')
op.push(ch);
else if(Character.isDigit(ch)){
num.push(ch+"");
}
else if(ch == ')'){
while(op.size() != 0 && op.peek() != '('){
String b = num.pop();
String a = num.pop();
String ans = op.pop() + a + b;
num.push(ans);
}
op.pop();
}
else
op.push(ch);
}
while(num.size() > 0 && op.size() > 0){
String b = num.pop();
String a = num.pop();
String ans = op.pop() + a + b ;
num.push(ans);
}
String ans = num.pop();
return ans;
}
public void evaluate(String exp){
Stack<Integer> num = new Stack<>();
Stack<Character> op = new Stack<>();
for(int i = 0 ; i < exp.length() ; i++){
char ch = exp.charAt(i);
if(ch == '('){
op.push(ch);
}
if(Character.isDigit(ch)){
int num1 = ch - '0';
num.push(num1);
}
if(ch == '+' || ch == '-' || ch == '*' || ch == '/'){
while(op.size() != 0 && op.peek() != '(' && opVal(ch) <= opVal(op.peek())){
int n2 = num.pop();
int n1 = num.pop();
char ch1 = op.pop();
int val = value(n1 , n2 , ch1);
num.push(val);
}
op.push(ch);
}
if(ch == ')'){
while(op.size() != 0 && op.peek() != '('){
int n2 = num.pop();
int n1 = num.pop();
char ch1 = op.pop();
int val = value(n1 , n2 , ch1);
num.push(val);
}
op.pop();
}
}
while(op.size() != 0){
int n2 = num.pop();
int n1 = num.pop();
char ch1 = op.pop();
int val = value(n1 , n2 , ch1);
num.push(val);
}
System.out.println(num.pop());
System.out.println(post(exp));
System.out.println(pre(exp));
return;
}
} Editor is loading...