-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic-calculator-ii.js
49 lines (48 loc) · 1.48 KB
/
basic-calculator-ii.js
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
/**
* @param {string} s
* @return {number}
*/
var calculate = function(s) {
let stack = [];
let num = '';
let sign = null
// we loop till the full length of the array to account for last sign
for (let i = 0; i <= s.length; i++) {
const curr = s[i];
//handle space
if (curr === ' ') continue;
//if char is a number
if (!isNaN(curr)) num += curr;
//if we have a sign + - / *
if (isNaN(curr)) {
num = Number(num)
switch (sign) {
case '+':
case null:
//we push the initial number into the stack
stack.push(num)
break;
case '-':
//we push any values after the subtraction sign as negative
stack.push(-num)
break;
case '*':
//we pop the stack then multiply and push back
stack.push(stack.pop() * num)
break;
case '/':
//we pop the stack then devide and push back
stack.push(parseInt(stack.pop() / num, 10))
break;
}
// sign becomes current sign
sign = curr;
// we reset num
num = '';
}
}
//we reduce the array adding positive and negative numbers
return stack.reduce((a, b) => {
return a + b
}, 0)
};