-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0224-basic-calculator.js
More file actions
56 lines (52 loc) · 1.78 KB
/
0224-basic-calculator.js
File metadata and controls
56 lines (52 loc) · 1.78 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
/**
* Basic Calculator
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var calculate = function (s) {
const inputExpression = s;
const expressionLength = inputExpression.length;
const processingStack = [];
let currentCalculationTotal = 0;
let currentEvaluationSign = 1;
let stringTraversalIndex = 0;
while (stringTraversalIndex < expressionLength) {
const characterAtPointer = inputExpression[stringTraversalIndex];
if (characterAtPointer === " ") {
stringTraversalIndex++;
continue;
}
if (characterAtPointer >= "0" && characterAtPointer <= "9") {
let parsedNumericalValue = 0;
while (
stringTraversalIndex < expressionLength &&
inputExpression[stringTraversalIndex] >= "0" &&
inputExpression[stringTraversalIndex] <= "9"
) {
parsedNumericalValue =
parsedNumericalValue * 10 +
(inputExpression[stringTraversalIndex] - "0");
stringTraversalIndex++;
}
currentCalculationTotal += parsedNumericalValue * currentEvaluationSign;
continue;
} else if (characterAtPointer === "+") {
currentEvaluationSign = 1;
} else if (characterAtPointer === "-") {
currentEvaluationSign = -1;
} else if (characterAtPointer === "(") {
processingStack.push(currentCalculationTotal);
processingStack.push(currentEvaluationSign);
currentCalculationTotal = 0;
currentEvaluationSign = 1;
} else if (characterAtPointer === ")") {
const previousSignFromStack = processingStack.pop();
const previousTotalFromStack = processingStack.pop();
currentCalculationTotal =
previousTotalFromStack +
currentCalculationTotal * previousSignFromStack;
}
stringTraversalIndex++;
}
return currentCalculationTotal;
};