九度OJ 1019:简单计算器

来源:互联网 发布:廊坊百度快照优化推广 编辑:程序博客网 时间:2024/04/30 05:49

#include <iostream>#include <stack>#include <stdio.h>#include <string>#include <map>#include <vector>#include <regex>using namespace std;/*** 九度:1019:简单计算器* [10/9/2014 liu]*/// 1、将中缀表达式转换成前缀表达式或者是后缀表达式map<string,int> mapOperator;int getOperPriority(string a){// find函数返回的是一个迭代器std::map<string, int>::iterator pos;pos = mapOperator.find(a);return pos->second;}vector<string> split(string str, string pattern){vector<string> v;int size = str.length();str += pattern; // 这句话要注意while (str !=""){int index = str.find(pattern);string strtemp = str.substr(0, index);str.erase(0, index + 1);v.push_back(strtemp);}return v;}vector<string> centertopreExpression(vector<string> str){// mapOperator.insert(make_pair("+", 1));mapOperator.insert(make_pair("-", 1));mapOperator.insert(make_pair("*", 2));mapOperator.insert(make_pair("/", 2));// 3+4*5-4/3 // 定义两个栈stack<string> operatorStack; // 操作符栈stack<string> numStack; // 操作数栈for (int i = str.size() - 1; i >= 0; i--){if (isdigit(str[i][0])) // isdigit 判断字符{numStack.push(str[i]);}else{if (operatorStack.empty())operatorStack.push(str[i]);else{if (getOperPriority(str[i]) >= getOperPriority(operatorStack.top())){operatorStack.push(str[i]);}else{numStack.push(operatorStack.top());operatorStack.pop();while (!operatorStack.empty() && getOperPriority(str[i]) < getOperPriority(operatorStack.top())){numStack.push(operatorStack.top());operatorStack.pop();}operatorStack.push(str[i]);}}}}while(!operatorStack.empty()){numStack.push(operatorStack.top());operatorStack.pop();}int n = numStack.size();vector<string> strtemp; int temp = 0;while (!numStack.empty()){strtemp.push_back(numStack.top());numStack.pop();temp++;}return strtemp;}void calculate(stack<double> &intStack,string str){double a = intStack.top();intStack.pop();double b = intStack.top();intStack.pop();if (str == "*"){intStack.push(a*b);}else if (str == "/" ){intStack.push(a / b);}else if (str == "-"){intStack.push(a -b);}else if (str == "+"){intStack.push(a+b);}}int GetResult(string str){vector<string> strvec = split(str, " ");vector<string> resultstr = centertopreExpression(strvec);stack<double> intStack;for (int i = resultstr.size() - 1; i >= 0; i--){if (isdigit(resultstr[i][0])){int a = atoi(resultstr[i].c_str());intStack.push(a);}else{calculate(intStack, resultstr[i]);}}double a = intStack.top();return a;}int main(){string str;while (getline(cin,str)){printf("%d", GetResult(str));}return 0;}

上面的代码估计不能AC,做的题目太少,但是功能应该实现了

主要是使用了中缀表达式转换成前缀表达式,算是实现了一种算法,参考如下博客

http://blog.csdn.net/antineutrino/article/details/6763722


0 0
原创粉丝点击