首页 > 代码库 > 【Leetcode】Evaluate Reverse Polish Notation
【Leetcode】Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
栈的典型应用
1 class Solution { 2 public: 3 int evalRPN(vector<string> &tokens) { 4 int ans = 0; 5 stack<int> s; 6 for(int i = 0; i < tokens.size(); ++i) { 7 if (tokens[i] == "+") { 8 int b = s.top(); 9 s.pop();10 int a = s.top();11 s.pop();12 a += b;13 s.push(a);14 } else if (tokens[i] == "-") {15 int b = s.top();16 s.pop();17 int a = s.top();18 s.pop();19 a -= b;20 s.push(a);21 } else if (tokens[i] == "*") {22 int b = s.top();23 s.pop();24 int a = s.top();25 s.pop();26 a *= b;27 s.push(a);28 } else if (tokens[i] == "/") {29 int b = s.top();30 s.pop();31 int a = s.top();32 s.pop();33 a /= b;34 s.push(a);35 } else {36 s.push(atoi(tokens[i].c_str()));37 }38 }39 return s.top();40 }41 };
【Leetcode】Evaluate Reverse Polish Notation
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。