-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbasicCalculator.js
More file actions
90 lines (68 loc) · 1.71 KB
/
basicCalculator.js
File metadata and controls
90 lines (68 loc) · 1.71 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
87
88
89
90
/**
* @param {string}
* @return {number}
*/
var calculate = function(s) {
let str = removeSpaces(s);
function solve(left, right) {
let i = left;
let result = 0;
let operation = 1;
while (i <= right) {
if (str[i] === '(') {
let closeIndex = findCloseIndex(i, str);
result += operation * solve(i + 1, closeIndex - 1);
i = closeIndex + 1;
} else if (isDigit(str[i])) {
let numEndIndex = findNumEndIndex(i, str);
result += operation * parseInt(str.slice(i, numEndIndex));
i = numEndIndex;
} else if (str[i] === '-') {
operation = -1;
++i;
} else if (str[i] === '+') {
operation = 1;
++i;
}
}
return result;
}
return solve(0, str.length - 1);
};
function removeSpaces(s) {
let str = [];
for (let i = 0; i < s.length; ++i) {
if (s[i] !== ' ') {
str.push(s[i]);
}
}
return str.join('');
}
function findCloseIndex(openIndex, str) {
let balance = 0;
let i = openIndex;
while (i < str.length) {
if (str[i] === '(') {
++balance;
} else if (str[i] === ')') {
--balance;
}
if (balance === 0) {
return i;
}
++i;
}
}
function isDigit(char) {
return (char.charCodeAt() >= 48 && char.charCodeAt() <= 57);
}
function findNumEndIndex(startIndex, str) {
let i = startIndex;
while (i < str.length) {
if (isDigit(str[i])) {
++i;
} else {
return i;
}
}
}