-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathBasic Calculator II.java
52 lines (50 loc) · 1.67 KB
/
Basic Calculator II.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
// // https://leetcode.com/problems/basic-calculator-ii/
class Solution {
public int calculate(String s) {
int currentOperand = 0;
int num = 0;
int result = 0;
int prevNum = 0;
char operator = '+';
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
continue;
} if (s.charAt(i) >= 48 && s.charAt(i) <= 57) {
num = (num * 10) + (s.charAt(i) - 48);
} else if (s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '*' || s.charAt(i) == '/') {
if (operator == '+' || operator == '-') {
if (operator == '+'){
result += num;
prevNum = num;
} else {
result -= num;
prevNum = -num;
}
} else {
result -= prevNum;
if (operator == '*') {
result += prevNum * num;
prevNum = prevNum * num;
} else {
result += prevNum / num;
prevNum = prevNum / num;
}
}
operator = s.charAt(i);
num = 0;
}
}
if (operator == '+') {
result += num;
} else if (operator == '-') {
result -= num;
} else if (operator == '*') {
result -= prevNum;
result += prevNum * num;
} else {
result -= prevNum;
result += prevNum / num;
}
return result;
}
}