精華區beta Marginalman 關於我們 聯絡資訊
※ 引述《JerryChungYC (JerryChung)》之銘言: : https://leetcode.com/problems/evaluate-reverse-polish-notation : 150. Evaluate Reverse Polish Notation : 回傳逆波蘭表示法的結果值 : 有效運算子為 "+" "-" "*" "/" : 每個操作數會是整數或是另一個表達式 : 兩個整數之間的除法是向零截斷 : 不會有被零除的情況 : 答案和中間計算都可以用32位元整數表示 : Example 1: : Input: tokens = ["2","1","+","3","*"] : Output: 9 : Explanation: ((2 + 1) * 3) = 9 : Example 2: : Input: tokens = ["4","13","5","/","+"] : Output: 6 : Explanation: (4 + (13 / 5)) = 6 耍廢太久,要回來乖乖找工作了 我也來寫個 C++ code #include<unordered_set> class Solution { public: int evalRPN(vector<string>& tokens) { unordered_set<string> op = {"+", "-", "*", "/"}; stack<string> s; for (int i = 0; i < tokens.size(); ++i) { if (op.find(tokens[i]) == op.end()) s.push(tokens[i]); else { int num1 = stoi(s.top()); s.pop(); int num2 = stoi(s.top()); s.pop(); int ret = operate(num1, num2, tokens[i]); s.push(to_string(ret)); } } return stoi(s.top()); } int operate(int num1, int num2, string op) { if (op == "+") return num2+num1; else if (op == "-") return num2-num1; else if (op == "*") return num2*num1; else if (op == "/") return num2/num1; else return 0; } }; -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.227.197.109 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1706635201.A.6DD.html
oin1104: 好酷 01/31 01:23