標籤:九度
根據我的通過來看,首先這道題裡面沒有小數,如果存在除不盡的情況,也是按取整來算。
本題建立了兩個棧,一個儲存數位數字棧,一個儲存加減乘除的符號棧。在處理字串的時候,每次找到一個數字時,放進一個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 - 字串處理 - 計算運算式