首页 > 试题广场 >

表达式求值

[编程题]表达式求值
  • 热度指数:135169 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个字符串描述的算术表达式,计算出结果值。

输入字符串长度不超过 100 ,合法的字符包括 +, -, *, /, (, )0-9

数据范围:运算过程中和最终结果均满足 ,即只进行整型运算,确保输入的表达式合法

输入描述:

输入算术表达式



输出描述:

计算出结果值

示例1

输入

400+5

输出

405
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()){
        console.log(eval(line))
    }
}()

发表于 2024-09-09 16:37:32 回复(0)

这玩意没说不让用eval吧

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 a = 0;
    try {
      eval("a=" + line);
    } finally {
      console.log(a);
    }
  }
})();
发表于 2024-08-27 10:33:16 回复(0)
  • JS版本
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

const prio = {
    "(": 0,
    "+": 1,
    "-": 1,
    "*": 2,
    "/": 2,
};
function popAndCal(op, data) {
    const o = op.pop(),
        a = data.pop(),
        b = data.pop();
    switch (o) {
        case "+":
            data.push(a + b);
            break;
        case "-":
            data.push(b - a);
            break;
        case "*":
            data.push(a * b);
            break;
        case "/":
            data.push(b / a);
            break;
    }
}
function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
// 负数处理
function preProcess(s) {
    return s.replaceAll(/(?<![0-9\)])(?=-[0-9\(])/g, "0");
}
function cal(exp) {
    const len = exp.length;
    let i = 0,
        op = [],
        data = [];
    while (i < len) {
        const temp = exp[i];
        if (isNumber(temp)) {
            let j = i + 1;
            while (j < len && isNumber(exp[j])) {
                j++;
            }
            data.push(Number(exp.slice(i, j)));
            i = j;
            continue;
        } else if (!op.length) {
            op.push(temp);
        } else if (temp === "(") {
            op.push(temp);
        } else if (temp === ")") {
            while (op.length && op.at(-1) != "(") {
                popAndCal(op, data);
            }
            op.pop();
        } else {
            while (op.length && prio[op.at(-1)] >= prio[temp]) {
                popAndCal(op, data);
            }
            op.push(temp);
        }
        i++;
    }
    while (op.length) {
        popAndCal(op, data);
    }
    return data[0];
}
void (async function () {
    // Write your code here
    while ((line = await readline())) {
        // 先算()括号内,再算*/,最后算+-
        // const arr = line.match(/\(([^\)]\(*[0-9]+[^\(]\)*[\+\-\*\/]*)+\)/g);
        const exp = preProcess(line);
        const res = cal(exp)
        console.log(res)
        // console.log(eval(line))
    }
})();
发表于 2024-07-10 22:19:06 回复(0)
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()){
        console.log(eval(line))
    }
}()
发表于 2023-07-18 11:53:22 回复(1)
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()){
        // console.log(eval(line))
        console.log(Function(`return ${line}`)())
    }
}()

发表于 2023-03-27 13:54:52 回复(2)
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    // 两个栈 数字栈 符号栈
    const calc = (nums, ops) => {
        if (nums.length < 2 || ops.length === 0) return;
        let op = ops.pop();
        let b = +nums.pop();
        let a = +nums.pop();
        switch(op) {
            case '+':
                nums.push(a + b);
                break;
            case '-':
                nums.push(a - b);
                break;
            case '*':
                nums.push(a * b);
                break;
            case '/':
                nums.push(a / b);
                break;
        }
    }
    line = await readline();
    const opsMap = {
        '+': 1,
        '-': 1,
        '*': 2,
        '/': 2
    }
    const arr = line.split('');
    const nums = [0]; // 防止第一个数为负数
    const ops = [];
    for (let i = 0; i < arr.length; i++) {
        let cur = arr[i];
        if (cur === '(') {
            ops.push(cur);
            if (arr[i + 1]=== '-' || arr[i + 1] === '+') {// 处理负数
                nums.push(0);
            }
        } else if (cur === ')') {
            while(ops.length) {
                if (ops[ops.length - 1] !== '(') {// 栈顶不为左括号
                    calc(nums, ops)
                } else { // 栈顶为左括号,不需要运算,直接出栈
                    ops.pop();
                    break;
                }
            }
        } else {
            if(/\d/.test(cur)) {// 数字
                while(i + 1 < arr.length && /\d/.test(arr[i + 1])) {
                    cur += arr[i + 1];
                    i++;
                }
                nums.push(cur);
            } else {// 加减乘除运算符
                // 加减乘除
                while(ops.length && ops[ops.length - 1] !== '(') {
                    const topOp = ops[ops.length - 1];
                    if (opsMap[topOp] >= opsMap[cur]) {// 栈顶元素与当前运算符优先级相等的话,直接取栈顶运算符计算
                        calc(nums, ops);
                    } else {
                        break;
                    }
                }
                ops.push(cur)
            }
        }
    }
    while (ops.length) calc(nums, ops);
    console.log(nums[nums.length - 1])
}()

发表于 2023-03-25 18:33:35 回复(0)
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    console.log(eval(line = await readline()))
}()

发表于 2022-12-23 13:45:12 回复(1)

问题信息

难度:
8条回答 43882浏览

热门推荐

通过挑战的用户

表达式求值