// 演算法：與 C 版相同，用 std::stack<int> 暫存數字。
// Algorithm: same as the C version, using std::stack<int> to hold numbers.
// 數字 push；運算子 pop 兩個、計算、push 回結果；最後堆疊頂端即答案。
// Push numbers; on operators pop two, compute, push back; the final top is the answer.

#include <stack>     // 提供 std::stack 容器 / provides the std::stack container.
#include <string>    // 提供 std::string 與 std::stoi / provides std::string and std::stoi.
#include <vector>    // 函式參數用 vector / parameter uses a vector.

class Solution {
public:
    int evalRPN(std::vector<std::string>& tokens) {
        std::stack<int> st;  // 宣告一個整數堆疊 / declare a stack of ints.

        // range-for：依序取出 tokens 裡的每個字串。const& 避免複製字串。
        // range-for: iterate over each string in tokens. const& avoids copying each string.
        for (const std::string& t : tokens) {

            // 判斷 t 是否為運算子。t == "+" 直接比較字串內容很直觀。
            // Check if t is an operator. std::string supports == for content comparison.
            if (t == "+" || t == "-" || t == "*" || t == "/") {

                int right = st.top();  // top() 看堆疊最上面的值（右運算元）/ top() reads the topmost value (right operand).
                st.pop();              // pop() 移除最上面的值，但本身不回傳 / pop() removes the top; it returns nothing.

                int left = st.top();   // 第二個取出的是左運算元 / the second one taken is the left operand.
                st.pop();

                int result;  // 本次運算結果 / result of this operation.

                // 用第一個字元 t[0] 判斷運算子並計算。
                // Decide and compute using the first character t[0].
                if      (t == "+") result = left + right;
                else if (t == "-") result = left - right;   // 左 - 右，順序不可顛倒 / left - right, order must not flip.
                else if (t == "*") result = left * right;
                else               result = left / right;   // 整數除法向 0 取整，符合題意 / int division truncates toward zero, as required.

                st.push(result);  // 把結果放回堆疊 / push the result back.
            } else {
                // 是數字：std::stoi 把字串轉成 int（可處理負號）。
                // A number: std::stoi parses the string into an int (handles negatives).
                st.push(std::stoi(t));
            }
        }

        return st.top();  // 堆疊僅剩的值就是答案 / the single remaining value is the answer.
    }
};
