Skip to content

Commit 53a7f4b

Browse files
authored
Update 227-basic-calculator-ii.js
1 parent 26bfa38 commit 53a7f4b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

227-basic-calculator-ii.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,36 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
const calculate = function(s) {
6+
const stk = []
7+
let op = '+', num = 0
8+
s = s.trim()
9+
const isDigit = ch => ch >= '0' && ch <= '9'
10+
for(let i = 0, n = s.length; i < n; i++) {
11+
const ch = s[i]
12+
if(ch === ' ') continue
13+
if(isDigit(ch)) {
14+
num = (+num) * 10 + (+ch)
15+
}
16+
if(!isDigit(ch) || i === n - 1) {
17+
if(op === '-') stk.push(-num)
18+
else if(op === '+') stk.push(num)
19+
else if(op === '*') stk.push(stk.pop() * num)
20+
else if(op === '/') stk.push(~~(stk.pop() / num))
21+
22+
op = ch
23+
num = 0
24+
}
25+
}
26+
let res = 0
27+
for(const e of stk) res += e
28+
29+
return res
30+
};
31+
32+
// another
33+
134
/**
235
* @param {string} s
336
* @return {number}

0 commit comments

Comments
 (0)