逆ポーランド記法 (paizaランク B 相当)
解答例
数字はスタックにためます。記号が来たら、スタックの末尾c2と末尾の隣c1の計算をします。計算はc1-c2の形式です。
const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");
const [N] = lines[0].split(" ").map(Number);
const A = lines[1].split(" ");//記号があるので文字列
let stack = [];
//Aの先頭から計算する
for (let i = 0; i < N; i++) {
if (A[i] === "+") {
let c2 = Number(stack.pop());
let c1 = Number(stack.pop());
stack.push(c1 + c2);
} else if (A[i] === "-") {
let c2 = Number(stack.pop());
let c1 = Number(stack.pop());
stack.push(c1 - c2);
} else {
stack.push(A[i]);
}
}
console.log(stack[0]);