forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasic Calculator.java
More file actions
55 lines (51 loc) · 1.41 KB
/
Basic Calculator.java
File metadata and controls
55 lines (51 loc) · 1.41 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
class Solution {
public static int calculate(String s) {
Stack<Integer> stack = new Stack<>();
int res = 0;
int num = 0;
int sign = 1;
boolean hasNumberStarted = false;
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
hasNumberStarted = true;
num = num * 10 + (int) (c - '0');
}
else if (c == '+') {
if(!hasNumberStarted) {
continue;
}
hasNumberStarted = false;
res += sign * num;
num = 0;
sign = 1;
}
else if (c == '-') {
if(!hasNumberStarted) {
sign *= -1;
continue;
}
hasNumberStarted = false;
res += sign * num;
num = 0;
sign = -1;
}
else if (c == '(') {
stack.push(res);
stack.push(sign);
sign = 1;
res = 0;
}
else if (c == ')') {
res += sign * num;
num = 0;
res *= stack.pop();
res += stack.pop();
}
}
if (num != 0) {
res += sign * num;
}
return res;
}
}