-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculator.java
32 lines (27 loc) · 1003 Bytes
/
Calculator.java
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
public class Calculator {
public double calculate(Node node) {
if (node == null) {
return 0;
}
if (node.operator == null) {
return node.operand;
}
switch (node.operator) {
case '+':
return calculate(node.left) + calculate(node.right);
case '-':
return calculate(node.left) - calculate(node.right);
case '*':
return calculate(node.left) * calculate(node.right);
case '^' :
return Math.pow(calculate(node.left),calculate(node.right));
case '/':
if (node.right.operand == 0) {
throw new IllegalArgumentException("Cannot divide by zero.");
}
return calculate(node.left) / calculate(node.right);
default:
throw new IllegalArgumentException("Invalid operator: " + node.operator);
}
}
}