多项式计算器-中缀变后缀并求值-C++版
2016-09-17 20:22
375 查看
闲着没事写了一个计算器回忆一下,支持加减乘除,括号,10以上的运算和负数。
不过没做错误判定,你的式子要是对的才行。。。
-19+(-3-(-11))*13+4/2
我的例子
因为最近用STL比较多,为了写起来方便,所以多了很多类型转换的地方,会影响一些效率,但是这个还是以实现功能为主吧。
不过没做错误判定,你的式子要是对的才行。。。
-19+(-3-(-11))*13+4/2
我的例子
因为最近用STL比较多,为了写起来方便,所以多了很多类型转换的地方,会影响一些效率,但是这个还是以实现功能为主吧。
class Solution { public: int calculate(string str){ vector<string> suffixVec; stack<char> charStack; for (int i = 0; i<str.size(); i++) { if (str[i] <= '9' && str[i] >='0') { string tmpStr = ""; tmpStr += str[i]; while(i+1<str.size()&&str[i+1]<='9'&&str[i+1]>='0'){ tmpStr += str[++i]; } suffixVec.push_back(tmpStr); }else if (str[i] == '/' || str[i] == '*' || str[i] == '('){ charStack.push(str[i]); }else if (str[i] == '+' || str[i] == '-'){ if(str[i] == '-' && ( i == 0 || str[i - 1] == '(')){ string tmpStr = ""; tmpStr += str[i]; while(i+1<str.size()&&str[i+1]<='9'&&str[i+1]>='0'){ tmpStr += str[++i]; } suffixVec.push_back(tmpStr); continue; } while ( !charStack.empty() &&(charStack.top() == '*' || charStack.top() == '/' || charStack.top() == '+' || charStack.top() == '-')) { string tmpStr = ""; tmpStr += charStack.top(); suffixVec.push_back(tmpStr); charStack.pop(); } charStack.push(str[i]); }else if (str[i] == ')'){ while (charStack.top() != '(') { string tmpStr = ""; tmpStr += charStack.top(); suffixVec.push_back(tmpStr); charStack.pop(); } charStack.pop(); } } while (!charStack.empty()) { string tmpStr = ""; tmpStr += charStack.top(); suffixVec.push_back(tmpStr); charStack.pop(); } stack<int> intStack; int tmpResult = 0; for (int i = 0; i<suffixVec.size(); i++) { string ss = suffixVec[i]; if ((ss[0] <= '9' && ss[0] >= '0' )||(ss[0] == '-' && ss.size() > 1)) { intStack.push(atoi(ss.c_str())); }else{ int a = intStack.top(); intStack.pop(); int b = intStack.top(); intStack.pop(); if (ss[0] == '+') { tmpResult = b + a; }else if (ss[0] == '-'){ tmpResult = b - a; }else if (ss[0] == '/'){ tmpResult = b / a; }else if (ss[0] == '*'){ tmpResult = b * a; } intStack.push(tmpResult); } } return tmpResult; } };
相关文章推荐
- C/C++的中缀转后缀并求值的实现
- 中缀表达式转后缀表达式(逆波兰式)的C++代码
- http://acm.nyist.net/JudgeOnline/problem.php?pid=409&&中缀转化为前缀和后缀并求值
- 递归下降来求解中缀或者后缀(C++)或者前缀表达式(scheme)
- 中缀表达式转后缀表达式并求值
- 中缀表达式到后缀表达式的转换C++实现
- 堆栈的应用(2) 中缀算术表达式到后缀(逆波兰记法reverse polish notation)的转换及其计算 C++实现
- C++实现中缀表达式转后缀表达式并求值
- 中缀转后缀,后缀求值,后缀构造表达式树
- 中缀转后缀求值
- 中缀表达式求后缀,再由后缀表达式求值
- 中缀转后缀表达式并求值
- 数据结构实验:一元多项式计算器(C++ 实现)
- 算术表达式求值(中缀转后缀,后缀求值,java 栈实现)
- 中缀、前缀和后缀表达式求值问题
- 数据结构_链表_稀疏多项式求值_C++实现
- 中缀转后缀&后缀求值
- c++ 直接中缀表达式求值 仅支持正整数的四则混合运算
- 线性表的实现与应用--表达式中缀转后缀并求值
- c++多项式计算器