Skip to content
文档章节

BM49 表达式求值

代码

ts
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 返回表达式的值
 * @param s string字符串 待计算的表达式
 * @return int整型
 */
const numStack = [];
const opStack = [];

export function solve(s) {
	const opMap = new Map();
	opMap.set('+', 1);
	opMap.set('-', 1);
	opMap.set('*', 2);
	opMap.set('/', 2);
	opMap.set('(', 0);
	opMap.set(')', 3);
	s = s.replace(' ', '');

	var len = s.length;
	var i = 0;

	while (i < len) {
		let char = s[i];
		if (isNumber(char)) {
			let value = '';
			while (isNumber(s[i]) && i < len) {
				value += s[i];
				i++;
			}
			numStack.push(Number(value));
		} else if (char === '(') {
			opStack.push('(');
			i++;
		} else if (char === ')') {
			while (opStack[opStack.length - 1] !== '(') {
				calc();
			}
			opStack.pop();
			i++;
		} else {
			if (!opStack.length) {
				opStack.push(char);
			} else if (opMap.get(char) > opMap.get(opStack[opStack.length - 1])) {
				opStack.push(char);
			} else {
				do {
					calc();
				} while (opMap.get(char) <= opMap.get(opStack[opStack.length - 1]));

				opStack.push(char);
			}
			i++;
		}
	}
	while (opStack.length) calc();
	return numStack[0];
}

function calc() {
	let num2 = numStack.pop();
	let num1 = numStack.pop();
	let op = opStack.pop();

	switch (op) {
		case '+':
			numStack.push(num1 + num2);
			break;
		case '-':
			numStack.push(num1 - num2);
			break;
		case '*':
			numStack.push(num1 * num2);
			break;
		case '/':
			if (num2 === 0) throw new Error('除数不能为0');
			numStack.push(num1 / num2);
	}
}

function isNumber(char) {
	return char >= '0' && char <= '9';
}