0
0

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 スタック・キューメニュー JavaScript 逆ポーランド記法

Last updated at Posted at 2023-01-16

逆ポーランド記法 (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]);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0