Skip to content

Commit d8655be

Browse files
authored
Update Basic Calculator III.java
1 parent ef5b325 commit d8655be

File tree

1 file changed

+24
-70
lines changed

1 file changed

+24
-70
lines changed

Hard/Basic Calculator III.java

Lines changed: 24 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,28 @@
11
class Solution {
2-
public int calculate(String s) {
3-
if (s.length() == 0) {
4-
return 0;
2+
public int calculate(String s) {
3+
int currNum = 0;
4+
int prevNum = 0;
5+
int result = 0;
6+
char operation = '+';
7+
for (int i = 0; i < s.length(); i++) {
8+
char c = s.charAt(i);
9+
if (Character.isDigit(c)) {
10+
currNum = currNum * 10 + Character.getNumericValue(c);
11+
}
12+
if ((!Character.isDigit(c) && !Character.isWhitespace(c)) || i == s.length() - 1) {
13+
if (operation == '-' || operation == '+') {
14+
result += prevNum;
15+
prevNum = operation == '+' ? currNum : -currNum;
16+
} else if (operation == '*') {
17+
prevNum = prevNum * currNum;
18+
} else {
19+
prevNum = prevNum / currNum;
520
}
6-
7-
Stack<Integer> nums = new Stack<>();
8-
Stack<Character> ops = new Stack<>();
9-
int num = 0;
10-
11-
for (int i = 0; i < s.length(); i++) {
12-
char c = s.charAt(i);
13-
if (c == ' ') {
14-
continue;
15-
}
16-
17-
if (Character.isDigit(c)) {
18-
num = c - '0';
19-
while (i < s.length() - 1 && Character.isDigit(s.charAt(i + 1))) {
20-
num = num * 10 + (s.charAt(i + 1) - '0');
21-
i++;
22-
}
23-
24-
nums.push(num);
25-
num = 0;
26-
}
27-
else if (c == '(') {
28-
ops.push(c);
29-
}
30-
else if (c == ')') {
31-
while (ops.peek() != '(') {
32-
nums.push(performOperation(ops.pop(), nums.pop(), nums.pop()));
33-
}
34-
ops.pop();
35-
}
36-
else if (c == '+' || c == '-' || c == '*' || c == '/') {
37-
while (!ops.isEmpty() && precedence(c, ops.peek())) {
38-
nums.push(performOperation(ops.pop(), nums.pop(), nums.pop()));
39-
}
40-
41-
ops.push(c);
42-
}
43-
}
44-
45-
while (!ops.isEmpty()) {
46-
nums.push(performOperation(ops.pop(), nums.pop(), nums.pop()));
47-
}
48-
49-
return nums.pop();
50-
}
51-
52-
private int performOperation(char op, int b, int a) {
53-
switch (op) {
54-
case '+': return a + b;
55-
case '-': return a - b;
56-
case '*': return a * b;
57-
case '/': return a / b;
58-
}
59-
60-
return 0;
61-
}
62-
63-
private boolean precedence(char op1, char op2) {
64-
if (op2 == '(' || op2 == ')') {
65-
return false;
66-
}
67-
68-
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
69-
return false;
70-
}
71-
72-
return true;
21+
operation = c;
22+
currNum = 0;
23+
}
7324
}
25+
result += prevNum;
26+
return result;
27+
}
7428
}

0 commit comments

Comments
 (0)