题解 | #逆波兰表达式求值#
逆波兰表达式求值
https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串一维数组 * @return int整型 */ function evalRPN( tokens ) { // write code here let numarr = []; for(let i of tokens) { // console.log(i); // console.log(!isNaN(Number(0))); if(!isNaN(Number(i))){ numarr.push(i) }else{ let tmp; let len = numarr.length; switch(i) { case '+': { tmp = Number(numarr[len - 2]) + Number(numarr[len - 1]); numarr.pop(); numarr.pop(); numarr.push(tmp); console.log(tmp); break; }; case '-': { tmp = Number(numarr[len - 2]) - Number(numarr[len - 1]); numarr.pop(); numarr.pop(); numarr.push(tmp); console.log(tmp); break; }; case '*': { tmp = Number(numarr[len - 2]) * Number(numarr[len - 1]); numarr.pop(); numarr.pop(); numarr.push(tmp); console.log(tmp); break; }; case '/': { tmp = parseInt(Number(numarr[len - 2]) / Number(numarr[len - 1])); numarr.pop(); numarr.pop(); numarr.push(tmp); console.log(tmp); break; }; } } } return numarr[0]; } module.exports = { evalRPN : evalRPN }; // 其实只要知道逆波兰表达式是什么就简单了
算法题合集 文章被收录于专栏
自己做算法的解题代码