標籤:style blog http io color ar for sp div
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
標籤:
stack;
這個問題是個尾碼運算式問題,用stack堆棧來解決最簡單有效。遇到數就將其壓入堆棧,遇到運算子號就從棧頂取出兩個數字參與運算。但是,要注意一個問題,每次彈出的兩個數,其正確的運算順序應該是後彈出的數在前,先彈出的數在後。舉例說明:
0 3 /
彈出的時候是3先彈出,0次之,本來是0/3,如果沒有按照正確的順序,就變成了3/0,程式就會因為出現嚴重錯誤而崩潰了!
感覺這個題目很簡單,但是因為上述的問題搞了很久才弄好,在編程之前,一定要多思考再動手!
貼出代碼:
1 int istoken(string s){ 2 if(s.compare("+")==0) 3 return 1; 4 if(s.compare("-")==0) 5 return 2; 6 if(s.compare("*")==0) 7 return 3; 8 if(s.compare("/")==0) 9 return 4;10 return -1;11 }//不同的傳回值對應不同的情況12 int transform(string s){13 return atoi(s.c_str());//將string轉換為int14 }15 class Solution {16 public:17 int evalRPN(vector<string> &tokens) {18 int len=tokens.size();19 int i;20 stack<int>end;21 for(i=0;i<len;i++){22 if(istoken(tokens[i])==-1){//將數壓入堆棧23 end.push(transform(tokens[i]));24 }25 else{26 int n1=end.top();27 end.pop();28 int n2=end.top();29 end.pop();//這裡n1,n2交換了順序30 switch(istoken(tokens[i])){31 case 1:{n1+=n2;break;}32 case 2:{n1-=n2;break;}33 case 3:{n1*=n2;break;}34 case 4:{n1/=n2;break;}35 }36 end.push(n1);37 }38 39 }40 return end.top();41 }42 };
Evaluate Reverse Polish Notation (5)