题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void (async function () {
// Write your code here
while ((line = await readline())) {
let st = line
.replace("[", "(")
.replace("]", ")")
.replace("{", "(")
.replace("}", ")");
// console.log(st);
function func(i) {
let nums = [];
let flag = null;
while (i < st.length) {
let num = 0;
if (st[i] == "(") {
[i, num] = func(i + 1);
}
while (i < st.length && /[0-9]/.test(st[i])) {
num = num * 10 + Number(st[i]);
i += 1;
}
if (nums.length == 0) {
nums.push(num);
}
if (flag == "+") {
nums.push(num);
} else if (flag == "-") {
nums.push(-num);
} else if (flag == "*") {
nums.push(nums.pop() * num);
} else if (flag == "/") {
nums.push(nums.pop() / num);
}
if (i < st.length && /[\+\-\*\/]/.test(st[i])) {
flag = st[i];
i++;
}
if (st[i] == ")") {
return [i + 1, sum(nums)];
}
}
return [i, sum(nums)];
}
function sum(arr) {
var s = 0;
for (var i = arr.length - 1; i >= 0; i--) {
s += arr[i];
}
return s;
}
console.log(func(0)[1]);
}
})();
