Skip to content

Commit 6c7a794

Browse files
authored
Update Basic Calculator.java
1 parent 711c922 commit 6c7a794

File tree

1 file changed

+37
-51
lines changed

1 file changed

+37
-51
lines changed

Hard/Basic Calculator.java

Lines changed: 37 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,41 @@
11
class Solution {
2-
public static int calculate(String s) {
3-
Stack<Integer> stack = new Stack<>();
4-
int res = 0;
5-
int num = 0;
6-
int sign = 1;
7-
boolean hasNumberStarted = false;
8-
9-
for (int i=0; i<s.length(); i++) {
10-
char c = s.charAt(i);
11-
12-
if (Character.isDigit(c)) {
13-
hasNumberStarted = true;
14-
num = num * 10 + (int) (c - '0');
15-
}
16-
else if (c == '+') {
17-
if(!hasNumberStarted) {
18-
continue;
19-
}
20-
hasNumberStarted = false;
21-
res += sign * num;
22-
num = 0;
23-
sign = 1;
24-
}
25-
else if (c == '-') {
26-
if(!hasNumberStarted) {
27-
sign *= -1;
28-
continue;
29-
}
30-
hasNumberStarted = false;
31-
res += sign * num;
32-
num = 0;
33-
sign = -1;
34-
}
35-
else if (c == '(') {
36-
stack.push(res);
37-
stack.push(sign);
38-
sign = 1;
39-
res = 0;
40-
}
41-
else if (c == ')') {
42-
res += sign * num;
43-
num = 0;
44-
res *= stack.pop();
45-
res += stack.pop();
46-
}
2+
public static int calculate(String s) {
3+
Stack<Integer> stack = new Stack<>();
4+
int res = 0;
5+
int num = 0;
6+
int sign = 1;
7+
boolean hasNumberStarted = false;
8+
for (int i = 0; i < s.length(); i++) {
9+
char c = s.charAt(i);
10+
if (Character.isDigit(c)) {
11+
hasNumberStarted = true;
12+
num = num * 10 + (int) (c - '0');
13+
} else if (c == '+' && hasNumberStarted) {
14+
hasNumberStarted = false;
15+
res += sign * num;
16+
num = 0;
17+
sign = 1;
18+
} else if (c == '-') {
19+
if(!hasNumberStarted) {
20+
sign *= -1;
21+
continue;
4722
}
48-
49-
if (num != 0) {
50-
res += sign * num;
51-
}
52-
53-
return res;
23+
hasNumberStarted = false;
24+
res += sign * num;
25+
num = 0;
26+
sign = -1;
27+
} else if (c == '(') {
28+
stack.push(res);
29+
stack.push(sign);
30+
sign = 1;
31+
res = 0;
32+
} else if (c == ')') {
33+
res += sign * num;
34+
num = 0;
35+
res *= stack.pop(); // For sign
36+
res += stack.pop(); // Adding the num in stack
37+
}
5438
}
39+
return res + (num != 0 ? sign * num : 0);
40+
}
5541
}

0 commit comments

Comments
 (0)