-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostfixExpression2.java
More file actions
73 lines (59 loc) · 2.13 KB
/
Copy pathPostfixExpression2.java
File metadata and controls
73 lines (59 loc) · 2.13 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
package org.example.Algorithm.test;
import java.util.*;
public class PostfixExpression2 {
private static final String MULTIPLICATION = "*";
private static final String PLUS = "+";
private static final String MINUS = "-";
private static final String DIVISION = "/";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String postExpression = sc.next();
Queue<Integer> operands = new LinkedList<>();
for (int i = 0; i < N; i++) {
operands.add(sc.nextInt());
}
Double value = operationOfInfixExpression(postExpression, operands);
String result = String.format("%.2f", value);
System.out.println(result);
sc.close();
}
private static Double operationOfInfixExpression(String postExpression, Queue<Integer> operands) {
Map<String, Double> map = new HashMap<>();
Stack<Double> stack = new Stack<>();
for (int i = 0; i < postExpression.length(); i++) {
char c = postExpression.charAt(i);
String s = String.valueOf(c);
if (!Character.isLetter(c)) {
Double y = stack.pop();
Double x = stack.pop();
Double result = calculator(s, x, y);
stack.add(result);
} else {
Double findValue = map.get(s);
if (findValue == null) {
Double v = Double.valueOf(operands.remove());
map.put(s, v);
stack.add(v);
} else {
stack.add(findValue);
}
}
}
map.clear();
return stack.pop();
}
private static Double calculator(String operator, double x, double y) {
if (PLUS.equals(operator)) {
return x + y;
} else if (MINUS.equals(operator)) {
return x - y;
} else if (MULTIPLICATION.equals(operator)) {
return x * y;
} else if (DIVISION.equals(operator)) {
return x / y;
} else {
return null;
}
}
}