课程习题
1、四则运算
给定一个字符串,实现一个calc函数模拟四则运算并返回结果。
示例1:
输入:(1 + 2)
输出:3
示例2:
输入:((1 + 2) 3)
输出:9
示例3:
输入:((1 (1 + 2)) / 3)
输出:1注意:给定的表达式一定是整数运算且合法,不涉及小数。且全部使用小括号()表示其优先级。注意表达式可能带有空格
// 利用两个栈分别保存数值和运算符,当碰到右括号的时候出栈两个数值,并出栈一个操作符进行计算,将计算结果push进数值栈function calc (expression) {expression = expression.replace(/\s/g, '')const numberStack = []const operatorStack = []for (const char of expression) {if (char === ')') {const a = numberStack.pop()const b = numberStack.pop()const operator = operatorStack.pop()switch (operator) {case '+':numberStack.push(a + b)breakcase '-':numberStack.push(b - a)breakcase '*':numberStack.push(a * b)breakcase '/':numberStack.push(b / a)breakdefault:break}} else if (char === '+' || char === '-' || char === '*' || char === '/') {operatorStack.push(char)} else if (/\d/.test(char)) {numberStack.push(char * 1)}}return numberStack.pop()}
