-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
229 lines (193 loc) · 6.78 KB
/
Copy pathCalculator.java
File metadata and controls
229 lines (193 loc) · 6.78 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package algorithms.sprint2;
import static common.SafeParse.parseInt;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Deque;
/*
Принцип:
- Читаем токены ОПН слева направо.
- Если считанный символ - Число -> push в стек.
- Если считанный символ - Математическая Операция (+-*\) -> pop b, pop a, считаем a op b, push результат.
- Ответ: верх стека.
Корректность:
- В ОПН операция применяется к двум ближайшим слева операндам; к моменту чтения операции они лежат
на вершине стека. Мы заменяем эти два значения на результат, сохраняя корректное состояние.
- Деление требуется “вниз” (floor), поэтому используем Math.floorDiv(a, b).
Сложность:
- Время O(m), m — число токенов.
- Память - в худшем O(m)
*/
public class Calculator {
private static int eval(FastIn in) throws IOException {
Deque<Integer> st = new ArrayDeque<>();
while (true) {
String t;
try {
t = in.next();
} catch (EOFException e) {
break;
}
if (t.length() == 1) {
char op = t.charAt(0);
if (op == '+' || op == '-' || op == '*' || op == '/') {
if (st.size() < 2) {
throw new IllegalArgumentException("Operator requires two operands: " + op);
}
int b = st.pop();
int a = st.pop();
if (op == '/' && b == 0) {
throw new IllegalArgumentException("Division by zero");
}
int r;
if (op == '+') {
r = a + b;
} else if (op == '-') {
r = a - b;
} else if (op == '*') {
r = a * b;
} else {
r = Math.floorDiv(a, b);
}
st.push(r);
continue;
}
}
try {
st.push(parseInt(t));
} catch (NumberFormatException exception) {
throw new IllegalArgumentException("Invalid token: " + t, exception);
}
}
if (st.size() != 1) {
throw new IllegalArgumentException("Expression must produce exactly one result");
}
return st.peek();
}
private static void run() throws Exception {
FastIn in = new FastIn(System.in);
FastOut out = new FastOut(System.out);
final int ans;
try {
ans = eval(in);
} catch (IllegalArgumentException exception) {
System.err.println("Invalid expression: " + exception.getMessage());
return;
}
out.writeInt(ans);
out.writeByte('\n');
out.flush();
}
// -------------------- LOCAL TESTS --------------------
private static void test() throws Exception {
assertEq(9, evalFromString("2 1 + 3 *"));
assertEq(38, evalFromString("7 2 + 4 * 2 +"));
assertEq(-1, evalFromString("-1 3 /"));
assertEq(-2, evalFromString("-4 3 /"));
assertEq(2, evalFromString("10 2 4 * -"));
assertEq(5, evalFromString("5"));
System.out.println("Test OK");
}
private static int evalFromString(String s) throws Exception {
InputStream is = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII));
return eval(new FastIn(is));
}
private static void assertEq(int exp, int act) {
if (exp != act) {
throw new AssertionError("Expected=" + exp + ", actual=" + act);
}
}
public static void main(String[] args) throws Exception {
if (System.getProperty("os.name").startsWith("Windows")) {
test();
} else {
run();
}
}
// -------------------- FAST INPUT --------------------
static final class FastIn {
private final InputStream in;
private final byte[] buf = new byte[1 << 16];
private int ptr = 0;
private int len = 0;
FastIn(InputStream in) {
this.in = in;
}
private int read() throws IOException {
if (ptr >= len) {
len = in.read(buf);
ptr = 0;
if (len <= 0) {
return -1;
}
}
return buf[ptr++];
}
String next() throws IOException {
int c;
do {
c = read();
if (c == -1) {
throw new EOFException("EOF");
}
} while (c <= ' ');
byte[] tmp = new byte[32];
int n = 0;
while (c > ' ') {
if (n == tmp.length) {
byte[] t2 = new byte[tmp.length << 1];
System.arraycopy(tmp, 0, t2, 0, tmp.length);
tmp = t2;
}
tmp[n++] = (byte) c;
c = read();
if (c == -1) {
break;
}
}
return new String(tmp, 0, n, StandardCharsets.UTF_8);
}
}
// -------------------- FAST OUTPUT --------------------
static final class FastOut {
private final OutputStream out;
private final byte[] buf = new byte[1 << 16];
private int p = 0;
private final byte[] tmp = new byte[12];
FastOut(OutputStream out) {
this.out = out;
}
void writeByte(int b) throws IOException {
if (p == buf.length) {
flush();
}
buf[p++] = (byte) b;
}
void writeInt(int x) throws IOException {
if (x == 0) {
writeByte('0');
return;
}
if (x < 0) {
writeByte('-');
x = -x;
}
int k = 0;
while (x > 0) {
tmp[k++] = (byte) ('0' + (x % 10));
x /= 10;
}
for (int i = k - 1; i >= 0; i--) {
writeByte(tmp[i]);
}
}
void flush() throws IOException {
out.write(buf, 0, p);
p = 0;
}
}
}