Skip to content

Commit a6835c8

Browse files
authored
Update 224-basic-calculator.js
1 parent 45fb60a commit a6835c8

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

224-basic-calculator.js

+43
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,46 @@ const calculate = function(s) {
3434
}
3535
return res + sign * num
3636
}
37+
38+
// another
39+
40+
/**
41+
* @param {string} s
42+
* @return {number}
43+
*/
44+
const calculate = function(s) {
45+
s = s.split(' ').join('')
46+
const n = s.length, stack = []
47+
const isNum = ch => ch >= '0' && ch <= '9'
48+
let num = 0, op = 1, res = 0
49+
for(let i = 0; i < n; i++) {
50+
const ch = s[i]
51+
if(isNum(ch)) {
52+
num = num * 10 + (+ch)
53+
} else {
54+
if(ch === '(') {
55+
stack.push(res)
56+
stack.push(op)
57+
num = 0
58+
op = 1
59+
res = 0
60+
} else if(ch === ')') {
61+
res += num * op
62+
res *= stack.pop()
63+
res += stack.pop()
64+
num = 0
65+
op = 1
66+
} else if(ch === '+') {
67+
res += op * num
68+
op = 1
69+
num = 0
70+
} else if(ch === '-') {
71+
res += op * num
72+
op = -1
73+
num = 0
74+
}
75+
}
76+
}
77+
78+
return res + op * num
79+
};

0 commit comments

Comments
 (0)