Basic Calculator II
生活随笔
收集整理的這篇文章主要介紹了
Basic Calculator II
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? 該題和前面的"
Basic Calculator
"的處理方法一樣,僅僅是增加了對(duì)"*"、"/"兩種運(yùn)算的支持。class Solution { public:bool isnum(char c){if(c >= '0' && c <= '9')return true;return false;}int calculate(string s) { vector<string> postorder;stack<char> ccache;stack<int> icache;string tmp;if(s.length() < 1)return 0; //構(gòu)造后綴表達(dá)式for(int i = 0; i < s.length(); ){if(s[i] == ' '){i++;continue;}if(!isnum(s[i])){if(s[i] == '(' || ccache.empty()){ccache.push(s[i]);i++;continue;}if(s[i] == ')'){while(ccache.top() != '('){tmp = "";tmp += ccache.top();postorder.push_back(tmp);ccache.pop();}ccache.pop();i++;continue;}if(s[i] == '+' || s[i] == '-'){while(!ccache.empty() && ccache.top() != '(' ){tmp = "";tmp += ccache.top();postorder.push_back(tmp);ccache.pop();}ccache.push(s[i]);i++;continue;}if(s[i] == '*' || s[i] == '/'){while(!ccache.empty() && ccache.top() != '(' && ccache.top() != '+' && ccache.top() != '-'){tmp = "";tmp += ccache.top();postorder.push_back(tmp);ccache.pop();}ccache.push(s[i]);i++;continue;}}else{int j = i;while(j < s.length() && isnum(s[j]))j++;tmp = "";tmp = s.substr(i, j - i);postorder.push_back(tmp);i = j;}} //加入全部剩余的元素while(!ccache.empty()){tmp = "";tmp += ccache.top();ccache.pop();postorder.push_back(tmp);} //通過(guò)后綴表達(dá)式計(jì)算結(jié)果值int fir, sec, result;for(int i = 0; i < postorder.size(); i++){if(postorder[i] == "+" || postorder[i] == "-" || postorder[i] == "*" || postorder[i] == "/"){sec = icache.top();icache.pop();fir = icache.top();icache.pop();if(postorder[i] == "+")result = fir + sec;if(postorder[i] == "-")result = fir - sec;if(postorder[i] == "*")result = fir * sec;if(postorder[i] == "/")result = fir / sec;icache.push(result);}else{icache.push(atoi(postorder[i].c_str()));}}return icache.top();} };
轉(zhuǎn)載于:https://www.cnblogs.com/clnchanpin/p/7049935.html
總結(jié)
以上是生活随笔為你收集整理的Basic Calculator II的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。