-
Notifications
You must be signed in to change notification settings - Fork 16
/
BasicCalculatorII.java
88 lines (74 loc) · 2.68 KB
/
BasicCalculatorII.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
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
// https://leetcode.com/problems/basic-calculator-ii
// extremely innovative approach, using a grammar to evaluate expressions
// T: O(N)
// S: O(1)
import java.util.Set;
public class BasicCalculatorII {
private static final char ADDITION = '+';
private static final char SUBTRACTION = '-';
private static final char MULTIPLICATION = '*';
private static final char DIVISION = '/';
private static final char SPACE = ' ';
private static final Set<Character> ADDITIVE_OPERATORS = Set.of(ADDITION, SUBTRACTION);
private static final Set<Character> MULTIPLICATIVE_OPERATORS = Set.of(MULTIPLICATION, DIVISION);
private String expression;
private int index;
public int calculate(String s) {
this.expression = s;
this.index = 0;
return addition();
}
private int addition() {
int sum = multiplication();
while (index < expression.length() && isAdditiveOperator(expression.charAt(index))) {
char operator = expression.charAt(index++);
sum = applyOperator(sum, multiplication(), operator);
}
return sum;
}
private int multiplication() {
int result = toNumber();
while (index < expression.length() && isMultiplicativeOperator(expression.charAt(index))) {
char operator = expression.charAt(index++);
result = applyOperator(result, toNumber(), operator);
}
return result;
}
private int toNumber() {
int number = 0;
while (index < expression.length() && isDigitOrSpace(expression.charAt(index))) {
if (isSpace(expression.charAt(index))) {
index++;
continue;
}
number *= 10;
number += toDigit(expression.charAt(index));
index++;
}
return number;
}
private int toDigit(char digit) {
return digit - '0';
}
private boolean isDigitOrSpace(char c) {
return Character.isDigit(c) || isSpace(c);
}
private boolean isSpace(char c) {
return c == SPACE;
}
private int applyOperator(int a, int b, char operator) {
return switch (operator) {
case ADDITION -> a + b;
case SUBTRACTION -> a - b;
case MULTIPLICATION -> a * b;
case DIVISION -> a / b;
default -> throw new IllegalStateException("Unexpected value: " + operator);
};
}
private boolean isAdditiveOperator(char operator) {
return ADDITIVE_OPERATORS.contains(operator);
}
private boolean isMultiplicativeOperator(char operator) {
return MULTIPLICATIVE_OPERATORS.contains(operator);
}
}