0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

逆ポーランド記法

0
Posted at

今回は paiza の「逆ポーランド記法」の問題に挑戦!

🟦 問題概要

🔹 テーマ

  • 逆ポーランド記法(RPN) の計算
  • スタックを使って評価する

🔹 逆ポーランド記法とは?

中置記法(普段の式):

1 + 2
(1 + 2) - (3 + 4)

逆ポーランド記法:

1 2 +
1 2 + 3 4 + -

特徴:

  • 演算子が「後ろ」に来る
  • 括弧が不要
  • 計算順序が自動的に決まる

逆ポーランド記法



入力例:

3
1 2 +

出力例:

3






✅OK例:

const rl = require('readline').createInterface({ input: process.stdin });

const lines = [];
rl.on('line', line => lines.push(line));

rl.on('close', () => {
    const N = Number(lines[0]);
    const A = lines[1].split(' ');
    
    const stack = [];

    for (let i = 0; i < N; i++) {

        if (A[i] !== '+' && A[i] !== '-') {
            stack.push(Number(A[i]));
        } else {

            const a = stack.pop();
            const b = stack.pop();

            if (A[i] === '+') {
                stack.push(b + a);
            } else {
                stack.push(b - a);
            }
        }
    }
    
    console.log(stack[0]);
}); 

🔍コードの流れ

🔹 初期化

  • Nを取得
  • 式を配列にする
  • 空スタックを作る

🔹 ループ

各要素について:

  • 数字 → push
  • 演算子 →
    • a = pop
    • b = pop
    • b 演算子 a を計算
    • 結果を push

🔹 最後

  • stack[0] を出力






📝まとめ

🔹 ① スタックの基本動作

  • push
  • pop

🔹 ② LIFO(スタック) の意味

  • 後に入れた数が先に使われる

🔹 ③ 計算順序が超重要

b - a

であって

a - b

ではない。

🔹 やること

  • 式を左から順番に読む
  • 数字ならスタックに積む
  • 演算子なら
    • スタックから2つ取り出す
    • 計算する
    • 結果をスタックに積む
  • 最後にスタックに残る1つが答え
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?