Skip to content

Commit f29a417

Browse files
authored
Update 227-basic-calculator-ii.js
1 parent 54e8c90 commit f29a417

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

227-basic-calculator-ii.js

+40
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,43 @@ const calculate = function(s) {
2020

2121
return stack.reduce((ac, e) => ac + e, 0)
2222
};
23+
24+
// another
25+
26+
/**
27+
* @param {string} s
28+
* @return {number}
29+
*/
30+
const calculate = function(s) {
31+
if(s == null || s.length === 0) return 0
32+
let sum = 0, num = 0, op = '+', tmp = 0
33+
const stack = []
34+
for(let i = 0; i < s.length; i++) {
35+
const ch = s[i]
36+
const isInt = ch => ch >= '0' && ch <= '9'
37+
if(isInt(ch)) {
38+
num = num * 10 + (+ch)
39+
}
40+
if((!isInt(ch) && ch !== ' ') || i === s.length - 1) {
41+
if(op === '+') {
42+
sum += tmp
43+
tmp = num
44+
}
45+
else if(op === '-') {
46+
sum += tmp
47+
tmp = - num
48+
}
49+
else if(op === '*') {
50+
tmp *= num
51+
}
52+
else if(op === '/') {
53+
tmp = ~~(tmp / num)
54+
}
55+
op = ch
56+
num = 0
57+
}
58+
59+
}
60+
61+
return sum + tmp
62+
}

0 commit comments

Comments
 (0)