-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBasicCalculator_224.java
More file actions
40 lines (31 loc) · 887 Bytes
/
BasicCalculator_224.java
File metadata and controls
40 lines (31 loc) · 887 Bytes
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
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 224. Basic Calculator
~ Link : https://leetcode.com/problems/basic-calculator/
*/
class Solution {
public int calculate(String s) {
if(s == null) return 0;
int result = 0;
int sign = 1;
int num = 0;
Stack<Integer> stack = new Stack<Integer>();
stack.push(sign);
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c >= '0' && c <= '9') {
num = num * 10 + (c - '0');
} else if(c == '+' || c == '-') {
result += sign * num;
sign = stack.peek() * (c == '+' ? 1: -1);
num = 0;
} else if(c == '(') {
stack.push(sign);
} else if(c == ')') {
stack.pop();
}
}
result += sign * num;
return result;
}
}