Skip to content

Commit 1ab05ea

Browse files
committed
[leet] basic calculator
1 parent a55f0b3 commit 1ab05ea

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
var calculate = function (s) {
6+
let res = 0;
7+
let num = 0;
8+
let sign = 1;
9+
const stack = [];
10+
11+
for (let i = 0; i < s.length; i++) {
12+
const ch = s[i];
13+
14+
if (ch >= "0" && ch <= "9") {
15+
num = num * 10 + (ch.charCodeAt(0) - 48);
16+
} else if (ch === "+") {
17+
res += sign * num;
18+
num = 0;
19+
sign = 1;
20+
} else if (ch === "-") {
21+
res += sign * num;
22+
num = 0;
23+
sign = -1;
24+
} else if (ch === "(") {
25+
stack.push(res);
26+
stack.push(sign);
27+
res = 0;
28+
num = 0;
29+
sign = 1;
30+
} else if (ch === ")") {
31+
res += sign * num;
32+
num = 0;
33+
34+
const prevSign = stack.pop();
35+
const prevRes = stack.pop();
36+
37+
res = prevRes + prevSign * res;
38+
}
39+
}
40+
return res + sign * num;
41+
};

0 commit comments

Comments
 (0)