-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathKristina.java
More file actions
74 lines (67 loc) · 1.35 KB
/
Kristina.java
File metadata and controls
74 lines (67 loc) · 1.35 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
import java.util.*;
import java.io.*;
public class Kristina {
public static Integer evaluate(Integer a, Integer b, String op)
{
if (op.equals("^"))
{
return (int) Math.pow(a, b);
}
if (op.equals("*"))
{
return a * b;
}
if (op.equals("/"))
{
return a / b;
}
if (op.equals("+"))
{
return a + b;
}
return a - b;
}
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(new File("kristina.dat"));
int n = scan.nextInt();
scan.nextLine();
while (n-- > 0)
{
String[] exp = scan.nextLine().split(" ");
String ops = "^*/+-";
Stack<Integer> stack = new Stack<>();
if (exp[0].equals("PRE"))
{
for (int i = exp.length-1; i > 0; i--)
{
if (!ops.contains(exp[i]))
{
stack.push(Integer.parseInt(exp[i]));
}
else
{
stack.push(evaluate(stack.pop(), stack.pop(), exp[i]));
}
}
System.out.println(stack.peek());
}
else
{
for (int i = 1; i < exp.length; i++)
{
if (!ops.contains(exp[i]))
{
stack.push(Integer.parseInt(exp[i]));
}
else
{
Integer b = stack.pop();
Integer a = stack.pop();
stack.push(evaluate(a, b, exp[i]));
}
}
System.out.println(stack.peek());
}
}
}
}