-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0772-basic-calculator-iii.js
More file actions
86 lines (75 loc) · 2.4 KB
/
0772-basic-calculator-iii.js
File metadata and controls
86 lines (75 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Basic Calculator III
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var calculate = function (s) {
let globalParseIndex = 0;
const inputExpressionString = s;
const skipWhitespaceCharacters = () => {
while (
globalParseIndex < inputExpressionString.length &&
inputExpressionString[globalParseIndex] === " "
) {
globalParseIndex++;
}
};
const parseAtomicFactor = () => {
skipWhitespaceCharacters();
let currentFactorValue = 0;
if (inputExpressionString[globalParseIndex] === "(") {
globalParseIndex++;
const recursiveExpressionResult = evaluateCurrentExpression();
globalParseIndex++;
return recursiveExpressionResult;
}
while (
globalParseIndex < inputExpressionString.length &&
inputExpressionString[globalParseIndex] >= "0" &&
inputExpressionString[globalParseIndex] <= "9"
) {
currentFactorValue =
currentFactorValue * 10 +
parseInt(inputExpressionString[globalParseIndex]);
globalParseIndex++;
}
return currentFactorValue;
};
const processMultiplicationDivision = () => {
let termSubtotal = parseAtomicFactor();
while (globalParseIndex < inputExpressionString.length) {
skipWhitespaceCharacters();
const operationSign = inputExpressionString[globalParseIndex];
if (operationSign !== "*" && operationSign !== "/") {
break;
}
globalParseIndex++;
const subsequentFactor = parseAtomicFactor();
if (operationSign === "*") {
termSubtotal *= subsequentFactor;
} else {
termSubtotal = Math.trunc(termSubtotal / subsequentFactor);
}
}
return termSubtotal;
};
const evaluateCurrentExpression = () => {
let expressionRunningTotal = processMultiplicationDivision();
while (globalParseIndex < inputExpressionString.length) {
skipWhitespaceCharacters();
const expressionOperationChar = inputExpressionString[globalParseIndex];
if (expressionOperationChar !== "+" && expressionOperationChar !== "-") {
break;
}
globalParseIndex++;
const nextTermComponent = processMultiplicationDivision();
if (expressionOperationChar === "+") {
expressionRunningTotal += nextTermComponent;
} else {
expressionRunningTotal -= nextTermComponent;
}
}
return expressionRunningTotal;
};
return evaluateCurrentExpression();
};