forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasic Calculator III.java
More file actions
74 lines (62 loc) · 2.04 KB
/
Basic Calculator III.java
File metadata and controls
74 lines (62 loc) · 2.04 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
class Solution {
public int calculate(String s) {
if (s.length() == 0) {
return 0;
}
Stack<Integer> nums = new Stack<>();
Stack<Character> ops = new Stack<>();
int num = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ' ') {
continue;
}
if (Character.isDigit(c)) {
num = c - '0';
while (i < s.length() - 1 && Character.isDigit(s.charAt(i + 1))) {
num = num * 10 + (s.charAt(i + 1) - '0');
i++;
}
nums.push(num);
num = 0;
}
else if (c == '(') {
ops.push(c);
}
else if (c == ')') {
while (ops.peek() != '(') {
nums.push(performOperation(ops.pop(), nums.pop(), nums.pop()));
}
ops.pop();
}
else if (c == '+' || c == '-' || c == '*' || c == '/') {
while (!ops.isEmpty() && precedence(c, ops.peek())) {
nums.push(performOperation(ops.pop(), nums.pop(), nums.pop()));
}
ops.push(c);
}
}
while (!ops.isEmpty()) {
nums.push(performOperation(ops.pop(), nums.pop(), nums.pop()));
}
return nums.pop();
}
private int performOperation(char op, int b, int a) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
return 0;
}
private boolean precedence(char op1, char op2) {
if (op2 == '(' || op2 == ')') {
return false;
}
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
return false;
}
return true;
}
}