-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path227-basic-calculator-ii.js
98 lines (96 loc) · 2.53 KB
/
227-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
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
87
88
89
90
91
92
93
94
95
96
97
98
/**
* @param {string} s
* @return {number}
*/
// var calculate = function (s) {
// const stack = [];
// const calc = (a, b, sign) => {
// if (sign === "+") return a + b;
// if (sign === "-") return a - b;
// if (sign === "*") return a * b;
// if (sign === "/") return Math.floor(a / b);
// };
// const isDigit = (str) => !isNaN(str);
// for (let i = 0; i < s.length; i++) {
// if (s[i] === " ") {
// continue;
// }
// // current item is a sign
// if (!isDigit(s[i])) {
// stack.push(s[i]);
// continue;
// }
// let newNumber = parseInt(s[i]);
// // current item is a number
// while (i + 1 < s.length && isDigit(s[i + 1])) {
// newNumber = newNumber * 10 + parseInt(s[i + 1]);
// i++;
// }
// const lastItem = stack[stack.length - 1];
// // last item is a number
// if (isDigit(lastItem)) {
// stack.push(newNumber);
// continue;
// }
// // last item is a sign and it is * or /
// if (lastItem === "*" || lastItem === "/") {
// const sign = stack.pop();
// const leftOperand = stack.pop();
// const result = calc(leftOperand, newNumber, sign);
// stack.push(result);
// continue;
// }
// // last item is a sign and it is + or -
// stack.push(newNumber);
// }
// while (stack.length !== 1) {
// const left = stack.shift();
// const sign = stack.shift();
// const right = stack.shift();
// const result = calc(left, right, sign);
// stack.unshift(result);
// }
// return stack[0];
// };
var calculate = function (s) {
let result = 0;
let prev = 0;
let i = 0;
let operation = "+";
while (i < s.length) {
if (s[i] === " ") {
i++;
continue;
}
if (isNaN(s[i])) {
operation = s[i];
i++;
continue;
}
let number = parseInt(s[i]);
while (i + 1 < s.length && !isNaN(s[i + 1]) && s[i + 1] !== " ") {
number = number * 10 + parseInt(s[i + 1]);
i++;
}
if (operation === "+") {
result += number;
prev = number;
} else if (operation === "-") {
result -= number;
prev = -number;
} else if (operation === "*") {
result -= prev;
result += prev * number;
prev = prev * number;
} else if (operation === "/") {
result -= prev;
result += Math.trunc(prev / number);
prev = Math.trunc(prev / number);
}
i++;
}
return result;
};
// console.error(calculate(" 3/2 "));
console.error(calculate("14-3/2"));
// console.error(calculate("1-1+1"));