国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

150. Evaluate Reverse Polish Notation

2019-11-08 03:05:12
字體:
來源:轉載
供稿:網友

題目

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 Subscribe to see which companies asked this question.


思路

用棧的出入來模擬后綴表達式的計算,注意入參合法性,除法時除數不能為0等場景


代碼

class Solution {public: bool isOperatorAndLegal(stack<int> &calStack,string &inputString) { if(calStack.size() < 2) { return false; } //長度不滿足運算符要求 if(inputString.size() != 1) { return false; } //不是合法運算符 char operatorChar = inputString.at(0); if(operatorChar != '+' && operatorChar != '-' && operatorChar != '*' && operatorChar != '/') { return false; } //除法的時候除數不能為0 if(operatorChar == '/' && calStack.top() == 0) { return false; } return true; } int getOperatorRslt(int firstNum,int secondNum,char operatorChar) { switch(operatorChar) { case '+': return firstNum + secondNum; case '-': return firstNum - secondNum; case '*': return firstNum * secondNum; case '/': return firstNum / secondNum; default: cout<<"getOperatorRslt,inputPara wrong,firstNum = "<<firstNum<<",secondNum = "<<secondNum <<",operatorChar = "<<operatorChar<<endl; return 0; } } int evalRPN(vector<string>& tokens) { //后綴表達式的計算,用棧 size_t length = tokens.size(); if(length == 0) { return 0; } if(length == 1) { return stoi(tokens[0]); } stack<int> calStack; int tempNum; int firstNum; int secondNum; char operatorChar; for(size_t i = 0;i < length;i++) { //也可以用C++11的stoi tempNum = atoi(tokens[i].c_str()); //字符串是0進棧,0的場景前提不包括多個0 if(tokens[i].size() == 1 && tokens[i].at(0) == '0') { calStack.push(0); continue; } //是數字就進棧 if(tempNum != 0) { calStack.push(tempNum); continue; } //是+,-,*,/且滿足當前棧要求 if(isOperatorAndLegal(calStack,tokens[i])) { operatorChar = tokens[i].at(0); secondNum = calStack.top(); calStack.pop(); firstNum = calStack.top(); calStack.pop(); calStack.push(getOperatorRslt(firstNum,secondNum,operatorChar)); } else { return 0; } } //最后要判斷當前棧是否只有一個元素 if(calStack.size() == 1) { return calStack.top(); } else { return 0; } }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 滨海县| 蒙阴县| 商水县| 霍州市| 石台县| 苗栗县| 治县。| 山丹县| 秦安县| 宁德市| 石渠县| 康保县| 中宁县| 德令哈市| 马尔康县| 京山县| 永川市| 牡丹江市| 龙井市| 阆中市| 南康市| 民乐县| 平安县| 青冈县| 乐平市| 汶上县| 平利县| 民和| 通州区| 唐海县| 沙雅县| 屏山县| 乡宁县| 内江市| 萍乡市| 大冶市| 正镶白旗| 福州市| 瑞昌市| 北宁市| 五河县|