九度 1101 - 字串處理 - 計算運算式

來源:互聯網
上載者:User

標籤:九度

根據我的通過來看,首先這道題裡面沒有小數,如果存在除不盡的情況,也是按取整來算。

本題建立了兩個棧,一個儲存數位數字棧,一個儲存加減乘除的符號棧。在處理字串的時候,每次找到一個數字時,放進一個string的臨時變數裡,因為會存在十位以上的情況;每次找到一個符號時,首先將string變數轉int放入數字棧,然後檢查符號棧的棧頂符號是否為乘或者除,如果是就從符號棧彈出頂,從數字棧彈出兩個數,計算後放回數字棧。這樣到處理完字串時,我們的符號棧內只剩下加和減了。此時不斷彈出符號與數字進行計算,直至符號棧為空白。此時數字棧的棧頂就是答案。

#include<iostream>#include<stack>#include<string>#include <stdlib.h>using namespace std;string data;string str="";int main(){while(cin>>data){data+='#'; //為了處理到最後一個數字時,仍能繼續處理,我們加一個#作為字串結尾。stack<int>n;stack<char>f;for(int i=0;data[i];i++){if(data[i]<='9'&&data[i]>='0'){str+=data[i];}else{n.push(atoi(str.c_str()));str="";if(!f.empty()){char tmp=f.top();if(tmp=='*'){f.pop();int a=n.top();n.pop();int b=n.top();n.pop();n.push(a*b);}else if(tmp=='/'){f.pop();int a=n.top();n.pop();int b=n.top();n.pop();n.push(b/a);}}if(data[i]!='#')f.push(data[i]);}}while(!f.empty()){char tmp=f.top();if(tmp=='+'){f.pop();int a=n.top();n.pop();int b=n.top();n.pop();n.push(a+b);}else if(tmp=='-'){f.pop();int a=n.top();n.pop();int b=n.top();n.pop();n.push(b-a);}}cout<<n.top()<<endl;}return 0;}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

九度 1101 - 字串處理 - 計算運算式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.