-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInfix Evaluation
More file actions
73 lines (67 loc) · 2.22 KB
/
Copy pathInfix Evaluation
File metadata and controls
73 lines (67 loc) · 2.22 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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();
Stack<Character> operators = new Stack<>();
Stack<Integer> operands = new Stack<>();
for (int i=0;i<exp.length();i++){
char ch = exp.charAt(i);
if (ch == '('){
operators.push(ch);
}else if (Character.isDigit(ch)){
operands.push(ch-'0');
}else if (ch == ')'){
while (operators.peek()!='('){
char optor = operators.pop();
int v2 = operands.pop();
int v1 = operands.pop();
int opv = operation(v1,v2,optor);
operands.push(opv);
}
operators.pop();
}
else if (ch == '+' || ch=='-' || ch == '/' || ch == '*'){
while (operators.size()>0 && operators.peek() != '(' && precedence(ch)<= precedence(operators.peek())){
char optor = operators.pop();
int v2 = operands.pop();
int v1 = operands.pop();
int opv = operation(v1,v2,optor);
operands.push(opv);
}
operators.push(ch);
}
}
while (operators.size() != 0){
char optor = operators.pop();
int v2 = operands.pop();
int v1 = operands.pop();
int opv = operation(v1,v2,optor);
operands.push(opv);
}
System.out.println(operands.peek());
}
public static int precedence(char oprator){
if(oprator =='+'){
return 1;
}else if(oprator =='-'){
return 1;
}else if(oprator =='*'){
return 2;
}else {
return 2;
}
}
public static int operation(int v1, int v2, char operator){
if (operator == '+'){
return v1+v2;
}else if (operator == '-'){
return v1-v2;
}else if (operator == '*'){
return v1*v2;
}else {
return v1/v2;
}
}
}