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
41 lines (41 loc) · 1.05 KB
/
Basic Calculator.java
File metadata and controls
41 lines (41 loc) · 1.05 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
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 == '+' && hasNumberStarted) {
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(); // For sign
res += stack.pop(); // Adding the num in stack
}
}
return res + (num != 0 ? sign * num : 0);
}
}