Evaluate Reverse Polish Notation (5)

來源:互聯網
上載者:User

標籤: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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.