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
原题地址
class Solution {
public:int evalRPN(vector<string> &tokens) {int ret=0;int n = tokens.size();if(n<=0) return ret;stack<int> s;int i=0;while(i<n){string temp = tokens[i];int num = atoi(temp.c_str());//防止非法输入if(num!=0 || (num==0 && temp[0]=='0')){s.push(num);}else{ret = cal(s, tokens[i][0]);if(ret == -1) return 0;}++i;}if(!s.empty()) p();else return 0;}int cal(stack<int> &s, char oper){if(s.size()<2) return -1;int op1 = s.top(); s.pop();int op2 = s.top(); s.pop();if(oper == '+'){s.push(op1+op2);}else if(oper == '-'){s.push(op2-op1);}else if(oper == '*'){s.push(op2 * op1);}else if(oper == '/'){if(op1 == 0) return -1;s.push(op2 / op1);}else return -1;return 0;}
};
本文发布于:2024-02-01 16:33:07,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170677638737973.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |