Skip to content

Commit 87e4857

Browse files
committed
Create 面试题 16.26. 计算器.js
1 parent 7262c5d commit 87e4857

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

面试题 16.26. 计算器.js

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
var calculate = function (s) {
6+
const priority = {
7+
'+': 1,
8+
'-': 2,
9+
'*': 3,
10+
'/': 3,
11+
};
12+
function isNumber(charCode) {
13+
const ZeroCharCode = '0'.charCodeAt(0);
14+
const NineCharCode = '9'.charCodeAt(0);
15+
return charCode >= ZeroCharCode && charCode <= NineCharCode;
16+
}
17+
function isOperator(char) {
18+
return ['+', '-', '*', '/'].includes(char);
19+
}
20+
function getResult(n1, n2, opr) {
21+
switch (opr) {
22+
case '+': {
23+
return n2 + n1;
24+
break;
25+
}
26+
case '-': {
27+
return n2 - n1;
28+
break;
29+
}
30+
case '*': {
31+
return n2 * n1;
32+
break;
33+
}
34+
case '/': {
35+
return Math.floor(n2 / n1);
36+
break;
37+
}
38+
}
39+
}
40+
41+
const numberStack = [];
42+
const operatorStack = [];
43+
let num = 0;
44+
for (let i = 0; i < s.length; i++) {
45+
if (isNumber(s.charCodeAt(i))) {
46+
num = num * 10 + +s[i];
47+
if (i === s.length - 1) {
48+
numberStack.push(num);
49+
}
50+
} else {
51+
if (isNumber(s.charCodeAt(i - 1))) {
52+
numberStack.push(num);
53+
num = 0;
54+
}
55+
56+
if (isOperator(s[i])) {
57+
while (
58+
operatorStack.length &&
59+
priority[operatorStack[operatorStack.length - 1]] >= priority[s[i]]
60+
) {
61+
numberStack.push(getResult(numberStack.pop(), numberStack.pop(), operatorStack.pop()));
62+
}
63+
operatorStack.push(s[i]);
64+
}
65+
}
66+
}
67+
68+
while (operatorStack.length) {
69+
numberStack.push(getResult(numberStack.pop(), numberStack.pop(), operatorStack.pop()));
70+
}
71+
72+
return numberStack[0];
73+
};

0 commit comments

Comments
 (0)