-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBasic Calculator.java
46 lines (45 loc) · 1.24 KB
/
Basic Calculator.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
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
char[] cs = s.toCharArray();
int num = 0;
int sign = 1;
int re = 0;
for(int i = 0; i < cs.length; i++){
if(Character.isDigit(cs[i])){
num = 10*num + cs[i]-'0';
}
if(cs[i] == '+'){
re += sign*num;
sign = 1;
num = 0;
}
if(cs[i] == '-'){
re += sign*num;
sign = -1;
num = 0;
}
if(cs[i] == '('){
// save previous and reset
stack.push(re);
stack.push(sign);
re = 0;
num = 0;
sign = 1;
}
if(cs[i] == ')'){
// mul sign and add before, reset
re += sign*num;
re *= stack.pop();
re += stack.pop();
num = 0;
sign = 1;
}
}
// if one character or for last character
if(num != 0){
re += sign*num;
}
return re;
}
}